| Author |
How to explain ?
|
Kay Liew
Ranch Hand
Joined: Dec 26, 2003
Posts: 112
|
|
Hi All, I am trying to play around with for loop printing and somehow the following loop not sync with my understanding. Can someone explain it for me? public class Test { public static void main(String[] args) { int x; for(x=1;x<9;x++) System.out.println("Hello" + x); System.out.println("x is : " + x); } } My expectation: Hello 1 x is 1 Hello 2 x is 2 Hello 3 x is 3 Hello 4 x is 4 so on .. up until Hello 9 x is 9 Actual printout. Hello1 Hello2 Hello3 Hello4 Hello5 Hello6 Hello7 Hello8 x is : 9 Why shoudn't 2 print statement get printed at the same time/loop? Thanks in advance, EQ
|
Unity can only be manifested by the Binary. Unity itself and the idea of Unity are already two.
|
 |
Signor Rana
Greenhorn
Joined: Jan 24, 2004
Posts: 4
|
|
Try now public class Test { public static void main(String[] args) { int x; for(x=1;x<9;x++) { // added 1 System.out.println("Hello" + x); System.out.println("x is : " + x); } //added 2 } } Here I added extra 2 line added 1 and added 2 now this makes your System.out.println as a one block which will be executed in each loop before only System.out.println("Hello" + x); is executed because by defult after for loop it only execute next line. Got it now! Have a fun
|
 |
Baps Vakkalagadda
Ranch Hand
Joined: May 25, 2004
Posts: 47
|
|
In Java, if you do not use braces for code blocks like 'for', 'if', etc, JVM treats only the immediate next line (terminated by as a part of it. JVM treats your code as:It means loops or conditions having only one statement do not require braces.
|
 |
Kay Liew
Ranch Hand
Joined: Dec 26, 2003
Posts: 112
|
|
Thank you to both of you. I know how the program flow but did not realize that's how JVM treat the for loop. I got it now. Baps, this statement makes a lot of sense for me. Thanks, EQ
|
 |
 |
|
|
subject: How to explain ?
|
|
|