Tutorial 32 and general question

0 Snir Cohen · September 3, 2015
Hey, 
In java tutorial 32- Arrays in Methods, I saw that after you made the' for statement' you didn't put the curly brackets- { } for whatever you wanted to do with the conditions..and I thought that they are needed whenever I use a for loop..
but there was no error msg and so I wonder how and when should I use or not use them after a for statement or if there are more exceptions to it.

Thanks

Post a Reply

Replies

Oldest  Newest  Rating
0 Snir Cohen · September 5, 2015
Thanks, got it.!

Just one thing- in the second bit of code you wrote the result would be 0, but I tried it and it gave me 1..it makes sense to me that the result would be 1 too..what am I missing here?

Thanks.
0 Dol Lod · September 5, 2015
Sorry, typo. That should be 1.
0 Dol Lod · September 4, 2015
You put brackets when you want to execute multiple lines of code for a given condition. You can use braces for one statement to be executed after a condition, but is optional.


int i=0;
int j=0;
if(j==0)
 i++;
j++;
System.out.println(i) would result in 1 with j also being equal to 1.

int i=0;
int j=0;
if(j==0)
{
i++;
}
j++;
System.out.println(i) would result in 1.
This is the same code as above except it uses braces for clarity.

int i=0;
int j=0;
if(j==1)
{
i=5;
j=6;
}
System.out.println(j) would print 6.
Here braces are necessary because if j==1, we want i to be 5 and j to equal 6 so they are different statements that we want to execute under the same condition.
  • 1

Java / Android Development

107,040 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator