• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to explain ?

 
Kay Liew
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Signor Rana
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic