Java MCQ
JAVA TRICKY static variables, static methods and static classes MCQ
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);
Static variables are shared among all instances. Changing through one object affects all objects.
What is the output of: class Test { static { System.out.print("S"); } { System.out.print("I"); } Test() { System.out.print("C"); } } new Test();
Static block runs first (when class loads), then instance block, then constructor when object is created.
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();
Static methods don't support runtime polymorphism. Method resolution is based on reference type, not object type.
What is the output of: class Test { static int x = 5; static { x = 10; } public static void main(String[] args) { System.out.println(x); } }
Static blocks execute in order they appear. The assignment x=10 in static block overwrites the initial value.
What is the output of: class Outer { static class Inner { void show() { System.out.print("Inner"); } } } Outer.Inner obj = new Outer.Inner(); obj.show();
What is the output of: class Test { static int count = 0; Test() { count++; } } new Test(); new Test(); System.out.println(Test.count);
Static variable count is shared among all instances and incremented each time constructor is called.
What is the output of: class Test { static int x = 5; int y = 10; static void show() { System.out.print(x + y); } } Test.show();
Static methods cannot access instance variables directly. They can only access static members.
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();
Static blocks run only once when class loads. Instance blocks run before each object creation.
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();
Static nested classes can access private static members of the outer class.
What is the output of: class Test { static final int x; static { x = 10; } static { x = 20; } } System.out.println(Test.x);
Static final variables can only be assigned once. The second assignment x=20 causes compilation error.