Q:

Java: Why is the result 5 and not 10?

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.

A:

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.

A:

It's because you declared i to be static. Therefore, all instances of B share the same value and memory location. (Therefore, there 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.

