This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Variable scope confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Variable scope confusion" Watch "Variable scope confusion" New topic
Author

Variable scope confusion

geeta rai
Ranch Hand

Joined: Sep 18, 2003
Posts: 48
class JMM125
{
static int i;
public static void main(String args[]) {
for (i=1; i<3; i++) {System.out.print(i);} // 1
for (int i=1; i<3; i++) {System.out.print(i);} // 2
int i; // 3
for (i=0; i<2; i++) {System.out.print(i);} // 4
System.out.print(JMM125.i);
}}
For the above code why would the value of variable i increase to 3 and would not be 0? The answer to the above question is 1212013 and not 1212010
dennis zined
Ranch Hand

Joined: Mar 07, 2003
Posts: 330
The last System.out.println refers to the static member variable i which was left with the value of 3 when the first for statement terminated. See code below.


SCJP 1.4<br />SCWCD 1.4
 
wood burning stoves
 
subject: Variable scope confusion
 
Similar Threads
Shadowing Doubt again?
Doubt in For loop
can anyone tell me the correct answer for the following question with explanation
Doubt in For Loop..
shadowing local variable