Java MCQ

Previous Java Multiple Choice Questions Next

JAVA TRICKY static variables, static methods and static classes MCQ

1

What is the output of: class Test { static int x = 10; } Test t1 = new Test(); Test t2 = new Test(); t1.x = 20; System.out.println(t2.x);

Correct Answer: B) 20

Static variables are shared among all instances. Changing through one object affects all objects.

2

What is the output of: class Test { static { System.out.print("S"); } { System.out.print("I"); } Test() { System.out.print("C"); } } new Test();

Correct Answer: A) SIC

Static block runs first (when class loads), then instance block, then constructor when object is created.

3

What is the output of: class A { static void show() { System.out.print("A"); } } class B extends A { static void show() { System.out.print("B"); } } A obj = new B(); obj.show();

Correct Answer: A) A

Static methods don't support runtime polymorphism. Method resolution is based on reference type, not object type.

4

What is the output of: class Test { static int x = 5; static { x = 10; } public static void main(String[] args) { System.out.println(x); } }

Correct Answer: B) 10

Static blocks execute in order they appear. The assignment x=10 in static block overwrites the initial value.

5

What is the output of: class Outer { static class Inner { void show() { System.out.print("Inner"); } } } Outer.Inner obj = new Outer.Inner(); obj.show();

Correct Answer: A) Inner

Static nested classes can be instantiated without an instance of the outer class.

6

What is the output of: class Test { static int count = 0; Test() { count++; } } new Test(); new Test(); System.out.println(Test.count);

Correct Answer: C) 2

Static variable count is shared among all instances and incremented each time constructor is called.

7

What is the output of: class Test { static int x = 5; int y = 10; static void show() { System.out.print(x + y); } } Test.show();

Correct Answer: C) Compilation error

Static methods cannot access instance variables directly. They can only access static members.

8

What is the output of: class Test { static { System.out.print("Static1 "); } static { System.out.print("Static2 "); } { System.out.print("Instance "); } } new Test(); new Test();

Correct Answer: A) Static1 Static2 Instance Instance

Static blocks run only once when class loads. Instance blocks run before each object creation.

9

What is the output of: class Outer { private static int x = 10; static class Inner { void show() { System.out.print(x); } } } new Outer.Inner().show();

Correct Answer: A) 10

Static nested classes can access private static members of the outer class.

10

What is the output of: class Test { static final int x; static { x = 10; } static { x = 20; } } System.out.println(Test.x);

Correct Answer: C) Compilation error

Static final variables can only be assigned once. The second assignment x=20 causes compilation error.

Previous Java Multiple Choice Questions Next