Question

-1 Jay Coltrain · October 1, 2014
On Java tutorial video 19 you did not use the curly brace in your if statement. What is the significance of using/not using them?

Post a Reply

Replies

Oldest  Newest  Rating
0 Son Truong · October 2, 2014
In conditional statements or loop statements like if, if-else, while, do while, for ... you must use curly brace when you have more than 2 statements in body. Otherwise when you have only 1 statement you must not use curly brace.

For example:



// Use curly brace
int sum = 0;
for (int i = 1; i <= 3; i++)
{
sum += i;
System.out.println("sum is: " + sum);
}

The result:


sum is: 1
sum is: 3
sum is: 6




// Don't use curly brace
int sum = 0;
for (int i = 1; i <= 3; i++)
sum += i;
System.out.println("sum is: " + sum);

The result:


sum is: 6



p/s: In my opinion you should use curly brace even when you have only 1 statement in body. That make your code is easy to reading or modifying.
0 Pere Garau Burguera · October 1, 2014
If there is only one line you don't need to put them (It works for if's, else's, for's, while's...)
0 Adrian W · October 1, 2014
It means that only the first line after the if statement "belongs" to it. e.g.
if (x > 0)
System.out.println("Hello");
System.out.println("Bye");

is equal to
if (x > 0){
System.out.println("Hello");
}
System.out.println("Bye");

The Result is always :
Hello
Bye

or just
Bye

depends on x
  • 1

Java / Android Development

107,322 followers
About

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

Links
Moderators
Bucky Roberts Administrator