0

I need an explanation for the output of the below code:

class Stats
{
    static int a = 10;
    int b = 20;
    void printMe()
    {
        System.out.println(a+b);
    }
}

public class Static
{
    public static void main(String args[])
    {
        Stats s1 = new Stats();
        Stats s2 = new Stats();
        s1.b = 30;
        s1.printMe();
        s1.a = 20;
        s2.printMe();
    }
}

Output: 40 40

I expected it to be 40 and 50 as there should be only one copy of static variable 'a' which is modified by through reference 's1' to 20.

Edward Falk
  • 9,991
  • 11
  • 77
  • 112
  • Static means affecting the entire class. There is only one `Stats.a` and only one `Stats.b`. It is therefore good practice to refer to static variables by class name instead of an instance name. – Justin Apr 27 '13 at 00:33
  • What you probably want are final variables. – Justin Apr 27 '13 at 00:34
  • @gangqinlaohu If you use Stats, I get 40 and 50 as output but static variable I believe should have only one copy. So, even if I alter it using an object reference, that single copy must get modified? –  Apr 27 '13 at 00:37
  • 3
    The first (s1) is 30 + 10 and the second (s2) is 20 + 20. BTW, did you hear about a wonderful tool called debugger ? – Nir Alfasi Apr 27 '13 at 00:37
  • Thanks, I got it now. –  Apr 27 '13 at 00:39
  • @alfasin yes the debugger can help but understanding the concept with an explanation is better. – Luiggi Mendoza Apr 27 '13 at 00:40
  • @alfasin A debugger, in cases like these, would only be an easier way of walking through code. I often don't use it, and just walk through my code in my head (because I'm to lazy to run it) – Justin Apr 27 '13 at 00:43
  • @gangqinlaohu and Luiggi Mendoza: I also rarely use a debugger, but if I can't figure it out by walking through the code, I would definitely use one before posting this question. Voting to close as "too localized" – Nir Alfasi Apr 27 '13 at 00:46
  • @alfasin I would say that it's a reasonable beginner Java question, but the OP probably should have searched the web for 'Java static variables' before asking the question. – Justin Apr 27 '13 at 00:47
  • @gangqinlaohu oh he KNOWS what static means: see the last two lines of the question :) – Nir Alfasi Apr 27 '13 at 00:49
  • @gangqinlaohu - There are as many Stats.b copies as there are instances of Stats. Only Stats.a is static. – Hot Licks Apr 27 '13 at 00:52
  • The reason you get the second 40 is that you're adding the 20 from a and the 20 from b in the second instance of Stats, that second b never having been modified from its initial value of 20. – Hot Licks Apr 27 '13 at 00:55

1 Answers1

4

a is static also called a "Class Variable", the value of a will be equal in all the instances of Stats,

so in the first call: a is equals to 10 and b is equals to 30 for s1, so a+b is equals to 40,

and in the second call: a is equals to 20 and b is equals to 20 for s2, so a+b is equals to 40

DGomez
  • 1,450
  • 9
  • 25