Java MCQ

Previous Java Multiple Choice Questions Next

JAVA TRICKY classes, objects MCQ

1

What is the output of: class Test { int x; } Test t = new Test(); System.out.println(t.x);

Correct Answer: A) 0

Instance variables of primitive types are automatically initialized to their default values (0 for int).

2

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.

3

What is the output of: class Test { { System.out.print("1"); } Test() { System.out.print("2"); } } new Test();

Correct Answer: A) 12

Instance initializer blocks run before the constructor when an object is created.

4

What is the output of: class Parent { Parent() { System.out.print("P"); } } class Child extends Parent { Child() { System.out.print("C"); } } new Child();

Correct Answer: A) PC

When creating a child object, the parent constructor is called first (implicit super() call).

5

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

Correct Answer: A) SI

Static blocks run when class is loaded (first use), instance blocks run before constructor when object is created.

6

What is the output of: class Test { Test() { this(10); System.out.print("1"); } Test(int x) { System.out.print("2"); } } new Test();

Correct Answer: B) 21

this(10) calls the parameterized constructor first, then the no-arg constructor continues execution.

7

What is the output of: class Test { String name; Test(String name) { this.name = name; } } Test t1 = new Test("A"); Test t2 = t1; t2.name = "B"; System.out.println(t1.name);

Correct Answer: B) B

t1 and t2 refer to the same object. Changing through one reference affects the same object.

8

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 and incremented each time constructor is called (each object creation).

9

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

Correct Answer: B) B

Runtime polymorphism - method called depends on actual object type (B), not reference type (A).

10

What is the output of: class Test { final int x; Test() { x = 10; } Test(int y) { System.out.print(x); } } new Test(5);

Correct Answer: C) Compilation error

Final instance variable x is not initialized in the parameterized constructor, causing compilation error.

Previous Java Multiple Choice Questions Next