Write a java program to swap two different values.
Answers
Answer:
-->with using third variable.
import java.util.*;
class Swap_With
{
public static void main(String[] args)
{
int x, y, t;// x and y are to swap
Scanner in = new Scanner(System.in);
System.out.println("Enter the value of X and Y");
x = in.nextInt();
y = in.nextInt();
System.out.println("before swapping numbers: "+x +" "+ y);
/*swapping */
t = x;
x = y;
y = t;
System.out.println("After swapping: "+x +" " + y);
System.out.println( );
}
}
--> without using third variable.
class NO_THIRD
{
public static void main(String arg[])
{
System.out.println("Before swapping");
int x = 10;
int y = 20;
System.out.println("value of x:" + x);
System.out.println("value of y:" + y);
System.out.println("After swapping");
x = x + y;
y = x - y;
x = x - y;
System.out.println("value of x:" + x);
System.out.println("value of y:" + y);
}
}
hope it helps ☺