Challenge: Swap Two Numbers

Lab Java Beginner 10 points

Start with int a = 5; and int b = 9;. Swap them so that a holds 9 and b holds 5, then print:

a = 9
b = 5

Input

None.

Output

The two lines above.

Example

Output

a = 9
b = 5
Sample output available
Editor
Java

Hints

Use a third variable, temp, to hold one value for a moment.

temp = a; then a = b; then b = temp;

Solution explanation

Like swapping the drinks in two glasses, you need a third, empty glass: temp.

Show solution
public class Main {
    public static void main(String[] args) {
        int a = 5;
        int b = 9;
        int temp = a;
        a = b;
        b = temp;
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD