Static variables in java

I have scenario like this

public class Test{

   static int a;
   int b;

   public static void main(String[] args){

      Test t1  = new Test();
      Test t2 = new Test();

   }
}

What will be the variables in object t1 and object t2?

As per my understanding since variable a is a static variable it will be both in object 1 and object 2.

And b will be created separate copy for both the objects.

But when I assign a value to variable b ie(int b=1) and call it like System.out.println(t1.b), System.out.println(t2.b)

Instead of getting an error I am getting 1 as output from both the objects.

Why is that?

Jon Skeet
people
quotationmark

As per my understanding since variable a is static variable it will be both in object 1 and object 2.

No. It's not in either object. It exists without reference to any particular instance at all. Although Java allows you to refer to it "via" a reference, e.g. int x = t1.a; you shouldn't do so. You should instead refer to it via the class name (test.a in your case - although you should also start following Java naming conventions) to make it clear that it's static.

And b will be created separate copy for both the objects.

Yes.

But when I assign a value to variable b ie(int b=1) and call it like System.out.println(t1.b), System.out.println(t2.b) Instead of getting an error I am getting 1 as output from both the objects.

Well that's because you've basically given it an initial value to assign for each new object. That's entirely reasonable. There are still two independent variables:

t1.b = 2;
t2.b = 3;
System.out.println(t1.b); // Prints 2
System.out.println(t2.b); // Prints 3

people

See more on this question at Stackoverflow