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

3.01K viewsJava
0

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

Answered question
Add a Comment
0

Try this logic..

int f = 10;
int s = 5;

f = f * s;
s = f / s;
f = x / s;

Changed status to publish
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

 

 

Posted new comment

Out put for this code is wrong guys pls upadte it

Manohar Kota

Updated, thanks for correcting me.

Add a Comment
Write your answer.