Question

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
Was it helpful?

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.

OTHER TIPS

Hint : Try to think about what's the use and the behavior of a static variable.

Read this :

Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

because, y is static so, first you assigned y=7.then 5 and finally 2. first value over ride to 5 then again over rides to 2.now current y value is 2. if you do not mention that value as static your output will be (g dot y=5) and (h dot y=2)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top