How to swap two values without using the third variable in java?

4.96K viewsJava
0

Please write a snippet code (logic) for how to swap two values without using the third variable?

Manohar Answered question July 8, 2019
Add a Comment
2

The values can be swapped using the sum and subtraction, try below snippet .

public class Test {

		public static void swapTwoValues(int firstVal, int secondVal) {

			System.out.println("Before swapping--->");
			System.out.println("First Value:" + firstVal);
			System.out.println("Second Value:" + secondVal);
			firstVal = firstVal + secondVal;
			secondVal = firstVal - secondVal;
			firstVal = firstVal - secondVal;
			System.out.println("After swapping---->");
			System.out.println("First Value:" + firstVal);
			System.out.println("Second Value:" + secondVal);

		}

		public static void main(String[] args) {
			int firstVal = 5;
			int secondVal = 6;
			swapTwoValues(firstVal, secondVal);

		}
	}

 

Output  :

Before swapping—>
First Value:5
Second Value:6
After swapping—->
First Value:6
Second Value:5

 

 

Manohar Posted new comment July 8, 2019

Out put for this code is wrong guys pls upadte it

Updated, thanks for correcting me.

Add a Comment
You are viewing 1 out of 2 answers, click here to view all answers.
Write your answer.