Reputation: 21
let a A.java file be :
class B {static int i; }
class A {
public static void main(String[] args) {
B a=new B();
B b=new B();
a.i=10;
b.i=5;
System.out.println(a.i);
}
}
Why is the result 5 and not 10 ?
Thanks.
Upvotes: 0
Views: 202
Reputation: 1060
Ill would say from this example that static says that whatever you are going to do with that int can only have one asigned value. So a.i and b.i just are different points of entry to the static int.
Upvotes: 0
Reputation: 19302
The value of a static member of a class is shared across all instances of a class.
Thus, when you set b.i=5, it also sets a.i to 5.
Note, that b.i and a.i actually share the same memory. So it's really "B.i" not a.i or b.i.
Upvotes: 1
Reputation: 471249
It's because you declared i
to be static. Therefore, all instances of (Therefore, there B
share the same value and memory location.B
is associated with the type rather than the instance.)
So when you do this:
a.i=10;
b.i=5;
You are actually writing to the value variable. Hence why 5
gets printed out instead of 10
.
Upvotes: 3
Reputation: 1500765
Because your variable is static. That means it's related to the type, not to any particular instance of the type. Your code is equivalent to:
// These are actually ignored as far as the subsequent lines are concerned.
// The constructor will still be executed, but nothing is going to read the
// values of variables "a" and "b".
B a = new B();
B b = new B();
// Note this is the *type name*.
B.i = 10;
B.i = 5;
System.out.println(B.i);
IMO it was a design mistake to allow access to static members via expressions like this - and in some IDEs (e.g. Eclipse) it can end up giving a warning or even an error if you so wish.
Upvotes: 6
Reputation: 7895
Because i is a static variable, it belong to the class, not to the objects of that class.
It's like a 'global' variable....study the 'static' keyword in java.
Good luck!
Upvotes: 2