Dremendo Tag Line

Swap numbers without using third variable in Java

Input - Question 10

In this question, we will see how to input two integers into two variables x and y in Java programming using the java input and swap their values without using a third variable. To knowTo know more about java input click on the java input lesson.

Q10) Write a program in Java to input two integers into two variables x and y and swap their values without using a third variable.

x = 5
y = 3

After Swap
x = 3
y = 5

Program

import java.util.Scanner;

public class Q10
{
    public static void main(String args[])
    {
        int x,y;
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter value of x ");
        x = sc.nextInt();
        System.out.print("Enter value of y ");
        y = sc.nextInt();
        x=x+y;
        y=x-y;
        x=x-y;
        System.out.println("After Swap");
        System.out.println("x=" + x);
        System.out.print("y=" + y);
    }
}

Output

Enter value of x 10
Enter value of y 20
After Swap
x=20
y=10
video-poster