What is the output of the following Java program?
class A
{
static int a=20,b=30;
A()
{
a++;
b++;
}
public void func()
{
System.out.println("a="+a+" b="+b);
}
}
public class Test
{
public static void main(String args[])
{
A a1=new A();
A a2=new A();
a1.func();
a2.func();
}
}
-
a=21 b=31
b=22 b=32
-
a=22 b=32
b=22 b=32
-
a=22 b=32
b=21 b=31
-
a=20 b=30
b=20 b=30
-
None of the above
B
Correct answer
Explanation
Static variable share common memory for different objects.All the object of a class having static variable will have same instance of static variable.Static variables are intialized only once.
Now according to program a,b are static variables and are intialized with integer values 20,30 respectively.
A a1=new A(); creates object a1, invokes constructor and increments both a and b. Now a=21 b=31 until a1 object creation
A a2=new A(); creates object a2, invokes again constructor and increments both a and b. Now a=22 b=32 until a2 object creation
a1.func(); //prints a=22. b=32 as a,b are static varibles
a2.func(); //prints a=22 b=32 as a,b are static varibles