0
0
Javaprogramming~15 mins

Static variables in Java - Practice Problems & Coding Challenges

Choose your learning style8 modes available
trophyChallenge - 5 Problems
🎖️
Static Variable Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 code output
intermediate
2:00remaining
Output 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);
    }
}
ACompilation error
B0
C1
D3
Attempts:
2 left
💻 code output
intermediate
2:00remaining
Static 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);
    }
}
A10\n10
B5\n5
C5\n10
DCompilation error
Attempts:
2 left
💻 code output
advanced
2:00remaining
Static 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);
    }
}
A1
BCompilation error: variable count might not have been initialized
CRuntime error: NullPointerException
D0
Attempts:
2 left
💻 code output
advanced
2:00remaining
Static 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);
    }
}
A2000
BLess than 2000
C1000
DCompilation error
Attempts:
2 left
🧠 conceptual
expert
2:00remaining
Static variable memory allocation
Which statement about static variables in Java is correct?
AStatic variables are stored in the method area and shared among all instances.
BStatic variables are stored in the stack and unique to each thread.
CStatic variables are stored in the heap and shared among all instances of the class.
DStatic variables are stored inside each object instance separately.
Attempts:
2 left