Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in the output of this program.

 
Pinki Roy
Greenhorn
Posts: 22
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Rancher
Posts: 1609
5
Android Java Java ME
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Joseph Mokenela
Ranch Hand
Posts: 66
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Pinki Roy
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joseph , Thank you so much for the clarification.
 
Anayonkar Shivalkar
Bartender
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic