Challenge: Swap Two Numbers
Completed
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
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
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module