Java Code To Check Swap with Variable

March 31, 2023

EXPLANATION:

    step1: Write the class name and declare the main method.

    step2: Initalize the variable int a,b,temp.

    step3: Give the value for the variable a=10,b=5.

    step4: Assign the third variable as temp.

    step5: Declare temp=a; a=b; b=temp;
                    
    step6: Assign a to a temp variable temp=a;

    step7: Assign b to a variable a=b;

    step8: Assign temp to variable b=temp;

    step9: Now, the value will be swapped. 

Program:

public class Swapvar 
{
	public static void main(String args[]) 
	{
		int a = 10;
		int b = 5;
		b = a + b;
		a = b - a;
		b = b - a;
		System.out.println(a);
		System.out.println(b);
	}

}

Compile:

javac Swapvar.java
 java Swapvar

Output:

5
10

You Might Also Like