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

5.02K 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
0

Try this logic..

int f = 10;
int s = 5;

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

Manohar Changed status to publish 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
Write your answer.