-->

9/19/2019

Write a Java Program to swap two numbers with using the third variable.

In this Example, we have made use of the Scanner class to declare an object with a predefined standard input object. This program will accept the values of x and y through the command line (when executed).

1import java.util.Scanner;
2 
3public class SwapTwoNumbers {
4 
5    public static void main(String[] args) {
6        // TODO Auto-generated method stub
7        int x, y, temp;
8        System.out.println("Enter x and y");
9        Scanner in = new Scanner(System.in);
10        x = in.nextInt();
11        y = in.nextInt();
12        System.out.println("Before Swapping" + x + y);
13        temp = x;
14        x = y;
15        y = temp;
16        System.out.println("After Swapping" + x + y);
17         
18    }
19 
20}
Output:
Enter x and y
45
98
Before Swapping4598
After Swapping9845
NEXT ARTICLE Next Post
PREVIOUS ARTICLE Previous Post
NEXT ARTICLE Next Post
PREVIOUS ARTICLE Previous Post