*
The moose likes Beginning Java and the fly likes Looping doubt    Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Looping doubt    " Watch "Looping doubt    " New topic
Author

Looping doubt

abin joy
Ranch Hand

Joined: Jul 29, 2008
Posts: 35
code
----------------------
case 0:
{

for (int x=10;x>5;x++)

if(x>10000000)

x=10;

break;

}
---------------------------
code

In the above given code why we have omitted the braces for the for loop even though a block of statements were there.How will the execution flow happen in this case?
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

please tell me what you get,the time of execution ?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18750
    
  40

In the above given code why we have omitted the braces for the for loop even though a block of statements were there.How will the execution flow happen in this case?


The "braces" are not required for the "for" loop. By default, the loop will execute the next line only. The braces are only necessary if you want to execute more than one line.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19672
    
  18

Originally posted by abin joy:

With proper indentation you can see the flow a lot better.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11246
    
  16

a "for" statement basically has two parts... the "for (;;) " part, followed by a statement or a block (curly braces).

an "if" statement basically has two parts... the "if (condition)" part, followed by a statement or a block (curly braces).

so, the compiler sees your "for (int x=10;x>5;x++)", and says "ok, put the next statement or block inside the loop.". the next thing it finds is the "if" statment, and so it take the whole thing - both parts - because that single statement has two parts.

[edit]Disable smilies. CR[/edit]
[ September 09, 2008: Message edited by: Campbell Ritchie ]

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Looping doubt