Java MCQ
JAVA TRICKY classes, objects MCQ
What is the output of: class Test { int x; } Test t = new Test(); System.out.println(t.x);
Instance variables of primitive types are automatically initialized to their default values (0 for int).
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 { { System.out.print("1"); } Test() { System.out.print("2"); } } new Test();
Instance initializer blocks run before the constructor when an object is created.
What is the output of: class Parent { Parent() { System.out.print("P"); } } class Child extends Parent { Child() { System.out.print("C"); } } new Child();
When creating a child object, the parent constructor is called first (implicit super() call).
What is the output of: class Test { static { System.out.print("S"); } { System.out.print("I"); } } new Test();
Static blocks run when class is loaded (first use), instance blocks run before constructor when object is created.
What is the output of: class Test { Test() { this(10); System.out.print("1"); } Test(int x) { System.out.print("2"); } } new Test();
this(10) calls the parameterized constructor first, then the no-arg constructor continues execution.
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);
t1 and t2 refer to the same object. Changing through one reference affects the same object.
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 and incremented each time constructor is called (each object creation).
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();
Runtime polymorphism - method called depends on actual object type (B), not reference type (A).
What is the output of: class Test { final int x; Test() { x = 10; } Test(int y) { System.out.print(x); } } new Test(5);
Final instance variable x is not initialized in the parameterized constructor, causing compilation error.