This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes problem with for loops Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "problem with for loops" Watch "problem with for loops" New topic

problem with for loops

nitya satheesh

Joined: Jan 25, 2013
Posts: 2
I have a problem with the for loops in the following program.It's a little silly but it's really bugging me..

class twoDArray{
public static void main(String args[]){
int twoD[]=new int[4][5];
int i,j,k=0;
for(i=0;i<4;i++)//why no curly braces here
system.out.println(twoD[i][j]+" ");

why doesn't the first for loop need any curly braces?
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11923

It's not just for loops. While loops are the same way.

According to the JLS, you can have exactly one 'thing' in the body of your loop. that thing can be (for example) a for-loop. Or an executable statement. Or a block of code surrounded by curly braces.

So, your first loop has one thing in it - a for-loop.

Now...just because you CAN leave those braces off doesn't mean you SHOULD. Pretty much everyone here is going to tell you to ALWAYS use them, whether they are strictly needed or not.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Jj Hill
Ranch Hand

Joined: Jul 25, 2011
Posts: 41

System should be capitalized..
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45338
Welcome to the Ranch
You ought to indent that code, then you would be able to see the relationships between the different parts. You should also tell us (for both your questions) where the question comes from.
Manu Somasekhar
Ranch Hand

Joined: May 22, 2012
Posts: 44
It is not a good practice to avoid braces like that.
nitya satheesh

Joined: Jan 25, 2013
Posts: 2
Thanks a lot!!!
I have one more question about this code.
The output of this code is supposed to be :
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19

but I get


Why this difference?

I got this code form a book called Complete reference :Java.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

you have to fiddle with System.out.print and System.out.println in some *rare* case nowadays...

Manu Somasekhar
Ranch Hand

Joined: May 22, 2012
Posts: 44
Hi nitya ,
what about changing


I agree. Here's the link:
subject: problem with for loops
It's not a secret anymore!