Write a program in java to swap two numbers without using third variable and with third variable.

with example...
Last updated:7/16/2019 11:19:50 PM

1 Answers

Anonymous User
Anonymous User

Swapping with the third variable:- 

Class mobile


{

public static void main(String args[])

{

int x = 10, int y = 21, int temp;

System.out.println('Before swapping '+x+', '+ + y);

temp=x;

x=y;

y=temp;

System.out.println('After swapping '+x+', '+ + y);

}

}

Output-

x=21

y=10.
Without third variable-


Class student

{

public static void main(String args[])

{

int x = 60;

 int y = 40;

System.out.println('Before swapping '+x+', '+ + y);

x=x+y;

y=x-y;

x=x-y;

System.out.println('After swapping '+x+', '+ + y);

}

}

Output-

x=40

y=60.

Answer