GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Simple 'for' loop question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Simple Watch "Simple New topic
Author

Simple 'for' loop question

Ben Jass
Ranch Hand

Joined: Sep 25, 2010
Posts: 76
This is an exercise out of the Head First Java 2nd Edition and I'm having trouble understanding the process of it.



output:
0 4
0 3
1 4
1 3
3 4
3 3

Every time the first for loop starts over, does the integer y get re-declared?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Yes. "y" exists only inside that inner "for" loop. As soon as that loop is through executing, it's as if "y" never existed. The next time around the outer loop, everything starts fresh, and you get a brand new copy of "y".


[Jess in Action][AskingGoodQuestions]
Ben Jass
Ranch Hand

Joined: Sep 25, 2010
Posts: 76


Thanks for helping with the first question. Now here's my other (probably last one, for now). When the statement 'break;' occurs in the code above, which loop does it break out of? Why?
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

break is used to get out of a for/while/do/switch loop. It gets out of the loop where the break lies in. In your example, it breaks from the for(int inner...) loop.


[My Blog]
All roads lead to JavaRanch
Ben Jass
Ranch Hand

Joined: Sep 25, 2010
Posts: 76
I appreciate it guys.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

It is also possible to break out of the outer loop, but you'll need a labeled break.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
GeeCON Prague 2014
 
subject: Simple 'for' loop question