This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in the output of this program. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in the output of this program." Watch "Doubt in the output of this program." New topic
Author

Doubt in the output of this program.

Pinki Roy
Greenhorn

Joined: May 16, 2008
Posts: 22

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

Joined: Jan 08, 2009
Posts: 1400
    
    6

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: 59

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: 1464
    
    5

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, OCEEJBD)
Pinki Roy
Greenhorn

Joined: May 16, 2008
Posts: 22
Joseph , Thank you so much for the clarification.
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1464
    
    5

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)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in the output of this program.
 
Similar Threads
Post increment operator
Chisolm mock exam query
Private modifier problem
How does thsi work
The i++ operator