Search code examples
javavariablesstatic-variables

Can't understand why this program gives me this output. Please explain me


When I run this program it gives me the following output. Why I getting g.y as 2 not 5. So why I getting this output? What I missed to understand. Please explain me.

public class G {

   public  int x = 3; 
   public static int y = 7; 

   public static void main(String[] args) {

       G g = new G();
       G h = new G();

       g.x=1;
       g.y=5;
       h.x=4;
       h.y=2;

       System.out.println("g.x="+g.x);    
       System.out.println("g.y="+g.y);
       System.out.println("h.x="+h.x);
       System.out.println("h.y="+h.y);

    } 
}

Output:

g.x=1
g.y=2
h.x=4
h.y=2

Solution

  • Static variables are one per entire class, not one per instance.

    Both g.y and h.y (and G.y) refer to the same variable, so the last assignment wins, and the value is 2.

    It is confusing to access a static variable via an instance of the class, but Java allows it.