Challenge - 5 Problems
Variable Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of variable initialization with expressions
What is the output of the following Java code?
Java
public class Main { public static void main(String[] args) { int a = 5; int b = a * 2; int c = b - a / 5; System.out.println(c); } }
Attempts:
2 left
💡 Hint
Remember the order of operations: division before subtraction.
✗ Incorrect
a = 5, b = 10 (5*2), c = 10 - (5/5) = 10 - 1 = 9
❓ Predict Output
intermediate2:00remaining
Value of variable after multiple declarations
What is the value of variable
num after running this code?Java
public class Main { public static void main(String[] args) { int num = 10; num = num + 5; num = num * 2; System.out.println(num); } }
Attempts:
2 left
💡 Hint
Follow the operations step by step.
✗ Incorrect
num starts at 10, then 10 + 5 = 15, then 15 * 2 = 30.
❓ Predict Output
advanced2:00remaining
Output with uninitialized local variable
What error or output does this code produce?
Java
public class Main { public static void main(String[] args) { int x; // System.out.println(x); // Uncommenting this line causes error x = 5; System.out.println(x); } }
Attempts:
2 left
💡 Hint
The variable is assigned before printing.
✗ Incorrect
Variable x is declared but not initialized at first. It is assigned 5 before printing, so output is 5.
❓ Predict Output
advanced2:00remaining
Output of variable shadowing in nested blocks
What is the output of this Java program?
Java
public class Main { public static void main(String[] args) { int val = 10; { int val = 20; System.out.println(val); } System.out.println(val); } }
Attempts:
2 left
💡 Hint
Java allows redeclaring a variable in an inner block (shadowing).
✗ Incorrect
Java does not allow redeclaring a local variable with the same name in an inner block. This causes a compilation error.
🧠 Conceptual
expert3:00remaining
Understanding default values of instance variables
Consider the following Java class. What is the output when
new Test().printValues(); is called?Java
public class Test { int a; boolean b; double c; String d; void printValues() { System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); } }
Attempts:
2 left
💡 Hint
Instance variables have default values if not initialized.
✗ Incorrect
Instance variables get default values: int=0, boolean=false, double=0.0, String=null.