Dremendo Tag Line

Swap numbers using third variable in Java

Input - Question 9

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 using a third variable z. To knowTo know more about java input click on the java input lesson.

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

x = 5
y = 3

After Swap
x = 3
y = 5

Program

import java.util.Scanner;

public class Q9
{
    public static void main(String args[])
    {
        int x,y,z;
        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();
        z=x;
        x=y;
        y=z;
        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