Challenge - 5 Problems
Static Variable Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of static variable increment
What is the output of the following Java code?
Java
public class Test { static int count = 0; public Test() { count++; } public static void main(String[] args) { Test t1 = new Test(); Test t2 = new Test(); Test t3 = new Test(); System.out.println(Test.count); } }
Attempts:
2 left
💡 Hint
Static variables are shared among all instances of a class.
✗ Incorrect
The static variable 'count' is incremented each time a new Test object is created. Since three objects are created, the final value is 3.
❓ Predict Output
intermediateStatic variable behavior with multiple classes
What will be printed when running this Java code?
Java
class A { static int x = 5; } class B extends A { static int x = 10; } public class Main { public static void main(String[] args) { System.out.println(A.x); System.out.println(B.x); } }
Attempts:
2 left
💡 Hint
Static variables are not overridden but hidden in subclasses.
✗ Incorrect
Class B declares its own static variable 'x' which hides A's 'x'. Accessing A.x prints 5, B.x prints 10.
❓ Predict Output
advancedStatic variable initialization order
What is the output of this Java code?
Java
public class Counter { static int count; static { count = count + 1; } public static void main(String[] args) { System.out.println(count); } }
Attempts:
2 left
💡 Hint
Static variables of type int are initialized to 0 by default before static blocks execute.
✗ Incorrect
Static int variables are initialized to 0 by default before the static initializer block runs. The block sets count = 0 + 1 = 1, so it prints 1.
❓ Predict Output
advancedStatic variable shared across threads
What is the output of this Java program?
Java
public class SharedCounter implements Runnable { static int counter = 0; public void run() { for(int i = 0; i < 1000; i++) { counter++; } } public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(new SharedCounter()); Thread t2 = new Thread(new SharedCounter()); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(counter); } }
Attempts:
2 left
💡 Hint
Incrementing a shared static variable without synchronization can cause race conditions.
✗ Incorrect
Both threads increment the static counter 1000 times each. Without synchronization, increments can overlap causing lost updates, so the final value is less than 2000.
🧠 Conceptual
expertStatic variable memory allocation
Which statement about static variables in Java is correct?
Attempts:
2 left
💡 Hint
Think about where class-level data is stored in Java memory model.
✗ Incorrect
Static variables belong to the class and are stored in the method area (part of JVM memory), shared by all instances. They are not stored in heap per instance or stack.
