| Author |
Doubt in the output of this program.
|
Pinki Roy
Greenhorn
Joined: May 16, 2008
Posts: 20
|
|
I don't understand why the second System.out.print(i);// output is 0 is producing the output 0.
Since i is a static variable I think it should have displayed 1. Please clarify.
|
 |
Swastik Dey
Ranch Hand
Joined: Jan 08, 2009
Posts: 1237
|
|
|
When you are calling that increment function, you are passing a value 0 to it. It gets the value in that parameter variable i (not the static variable i), increases that and returns the incremented value of the parameter variable, means the static variable i is still unaffected.
|
Swastik
|
 |
Joseph Mokenela
Ranch Hand
Joined: Jan 18, 2011
Posts: 58
|
|
Can you please clarify, the second println statement produces the output 1, not zero. In the future, please use the code tags when you post
a piece of code. It makes the code more readable.
What happens is that the method increments the local variable i, not that static variable because it has been
shadowed.
|
 |
Anayonkar Shivalkar
Bartender
Joined: Dec 08, 2010
Posts: 1295
|
|
Pinki Roy wrote:Since i is a static variable I think it should have displayed 1
1) int variables are never initialized to 1 automatically.
2) while automatically initializing a variable, only two things matter : a) if it is a class variable(method local variables are never initialized to default value, except arrays); b) data-type of that variable. It doesn't matter if the variable is static or not.
Besides this, why do you think first print statement should print 1?
|
Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD)
|
 |
Pinki Roy
Greenhorn
Joined: May 16, 2008
Posts: 20
|
|
Joseph , Thank you so much for the clarification.
|
 |
Anayonkar Shivalkar
Bartender
Joined: Dec 08, 2010
Posts: 1295
|
|
Joseph Mokenela wrote:method increments the local variable i, not that static variable because it has been shadowed.
and I thought Pinki Roy is concerned about output of first print statement (I got confused because statement and comments are exactly same)
|
 |
 |
|
|
subject: Doubt in the output of this program.
|
|
|