Interchange Program in Java
Two numbers are input through the keyboard into two locations A and B. Write a program to interchange the contents of A and B.
- The program starts by importing the java.util.Scanner package, which allows the user to input data into the program.
- Then, it declares two variables a and b of integer data type, which represent the values that the user inputs.
- The program then prompts the user to enter the values of a and b by displaying the message "Enter the A and B Numbers :". It takes the input using the Scanner object and stores it in their respective variables.
- Next, the program displays the values of a and b before the interchange using the System.out.println() method.
- Then, it declares a variable c and assigns it the value of a.
- The program then assigns the value of b to a and the value of c (which is the original value of a) to b, thereby interchanging the values of a and b.
- Finally, the program displays the values of a and b after the interchange using the System.out.println() method.
Overall, this program is a basic example of how Java can be used to interchange the values of two variables.
Source Code
import java.util.Scanner;
class Interchange
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the A and B Numbers :");
int a = input.nextInt();
int b = input.nextInt();
System.out.println("Before Interchange A : "+a+" || B : "+b);
int c = a;
a = b;
b = c;
System.out.println("After Interchange A : "+a+" || B : "+b);
}
}
Output
Enter the A and B Numbers :
23
18
Before Interchange A : 23 || B : 18
After Interchange A : 18 || B : 23