Is there a difference in removing the curly braces from If statements in java

JavaIf StatementCurly Braces

Java Problem Overview


While watching thenewbostons tutorial on basic java, he teaches us to do if statements like this.(Notice the curly Braces)

if("pie"== "pie"){
    System.out.println("Hurrah!");
}

So I tried removing the curly braces

if("pie"== "pie")
    System.out.println("Hurrah!");

And it still works! Since I'm new to java, I don't know why that works. And I want to know if removing(or adding) the curly braces give any benefits/disadvantages.

Java Solutions


Solution 1 - Java

For a single statement it will remain same, but if you want to group more than one statement in the if block then you have to use curly braces.

if("pie"== "pie"){
    System.out.println("Hurrah!");
    System.out.println("Hurrah!2");
}

if("pie"== "pie")
    System.out.println("Hurrah!"); //without braces only this statement will fall under if
    System.out.println("Hurrah!2"); //not this one

You should see: [Blocks in Java][1]

> A block is a group of zero or more statements between balanced braces > and can be used anywhere a single statement is allowed. The following > example, BlockDemo, illustrates the use of blocks:

class BlockDemo {
     public static void main(String[] args) {
          boolean condition = true;
          if (condition) { // begin block 1
               System.out.println("Condition is true.");
          } // end block one
          else { // begin block 2
               System.out.println("Condition is false.");
          } // end block 2
     }
}

(example from the above link) [1]: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html

Solution 2 - Java

No, there is absolutely no difference: a pair of curly braces makes multiple statements into a single one; if, while, for, and so on expect a single statement; if you need to guard only one statement, you do not need braces.

However, many software shops insist on having braces even for a single statement. The reason is errors like this:

if (x > 20)
    x -= 7;
    y -= 8;

The statements above are misleading: the indentation leads you to believe that both assignments are protected, while in reality only the first one is. The reason for that is that whitespace in Java is insignificant: indenting a statement does not change its placement in the overall flow of the program. Errors like the above are very hard to find, so adopting a rule to prevent them in the first place is a good idea.

Solution 3 - Java

As @rajesh says, braces are optional when the body is a single statement.

Having said that, leaving the braces in even for single statement cases is recommended by some coding styles because you (or the programmer who comes after you) are less likely to make errors when you change the code later.

if("pie"== "pie")
    System.out.println("Hurrah!");
    System.out.println("Tricked you");

The second print, Tricked you, is not actually in the if, it just looks like it because of the indentation.

However that is only a style point, not universally accepted, and certainly a competent programmer needs to be able to read both forms.

Solution 4 - Java

It does have a disadvantage. The answers mentioned so far are correct. But there are some disadvantages to it from the security perspective of things. Having worked in a payments team, security is a much stronger factor that motives such decisions. Lets say you have the following code:

if( "Prod".equals(stage) )
  callBankFunction ( creditCardInput )
else
  callMockBankFunction ( creditCardInput )

Now lets say you have this code is not working due to some internal problem. You want to check the input. So you make the following change:

if( "Prod".equals(stage) )
  callBankFunction ( creditCardInput )
else
  callMockBankFunction ( creditCardInput )
  Logger.log( creditCardInput )

Say you fix the problem and deploy this code (and maybe the reviewer & you think this won't cause a problem since its not inside the 'Prod' condition). Magically, your production logs now print customer credit card information that is visible to all the personnel who can see the logs. God forbid if any of them (with malicious intent) gets hold of this data.

Thus not giving a brace and a little careless coding can often lead to breach of secure information. It is also classified as a vulnerability in JAVA by CERT - Software Engineering Institure, CMU.

Solution 5 - Java

The curly braces are usually for having a block of statements. Without braces, only the first line will be executed in the if() statement. Not the entire block that starts with { and ends with }

if("pie" == "pie") {
   System.out.println("Executes if pie==pie");
   System.out.println("So does this");
}

and

if("pie" == "pie")
   System.out.println("Executes if pie==pie");
System.out.println("Executes, regardless of if pie is equal to pie");

Note however, if you want to compare two String objects, use .equals() method in String. This example still works because it is comparing one constant string with itself, which is always true.

Solution 6 - Java

This is a question of style that applies to a number of languages including Java, C++, C and C#.

When a code block contains only one line the braces can be omitted. This applies to any control structure: if, while, for, do-while.

For example, the two loops below are equivalent.

for(int i=0; i<100; i++)
  doSomething(i);



for(int i=0; i<100; i++) {
  doSomething(i);
}

Advantage of omitting {}: Your code can be briefer - meaning less line. Some may feel it is more readable.

Disadvantage of omitting {}: If you later modify your code and need to add another line to the code block, you better remember to add those {}. If not and you write the code below:

for(int i=0; i<100; i++)
  doSomething(i);
  doSomethingElse(i);

This is really equivalent to:

for(int i=0; i<100; i++) {
  doSomething(i);
}
doSomethingElse(i);

Solution 7 - Java

If there is only one statement after if then braces are not mandatory.

Now if you have a block of code which needs to fall under the if condition, then you need to use braces.

This holds good for loops as well

Solution 8 - Java

It's the same, if the number of sentences is equal to one. If there are more than one, you need the { } syntax

Solution 9 - Java

No BUT the real danger occurs when the code is edited later on. It is relatively easy to edit something like:

if (someCondition) 
    // do something 

to

if (someCondition) 
    // do something
    // do something else important

and think the 'do something else important' will only be run when someCondition is true. The indentation misleads :-)

With brackets, this danger isn't present.

Solution 10 - Java

My two cents. Writing two lines after an if statement without curly braces is a mistake I have never seen made. That said, the people you work with are bone heads who will not understand the magic trick you are pulling here. Save fun things like this for your private code, but do what you are told in professional and classroom settings.

There is one actual argument on this that illustrates a reasonable issue that might arise. As you may know, all indentation and extra whitespaces are removed from your code when it is being parsed. Troubles may arise when you try to use one-line else statements after multiple one-line if statements. For example:

if("cherry".equals("cherry"))
    if("pie".equals("pie"))
        System.out.println("Hurrah!");
else
    System.out.println("Rats!");

becomes indistinguishable from

if("cherry".equals("cherry"))
    if("pie".equals("pie"))
        System.out.println("Hurrah!");
    else
        System.out.println("Rats!");

Even in that circumstance, an automatic tabbing set up should indicate which if statement the else is pointing to, but it is something you should certainly be wary of should you choose to skirt the rules as I often do.

Solution 11 - Java

> And I want to know if removing(or adding) the curly braces give any benefits/disadvantages?

The advantage with adding them always is that you can simply extend the code block later, without needing to add them. Suppose you have:

if("pie".equals("pie"))
    System.out.println("Hurrah!");

then, if you want to add an additional line of code, you need to make sure to add the braces:

if("pie".equals("pie")) {
    log.debug("I am here!");
    System.out.println("Hurrah!");
}

If they are already there, simply put the cursor to the end of the line, press return and start adding new code.

For a single line, there is no difference technically, but many code conventions propose or even mandate to have them always there. There is even a CheckStyle rule for it.

Solution 12 - Java

For a single statement not an issue

if("pie"== "pie")
System.out.println("Hurrah!");

For two or more statements after if you require the braces

if("pie"== "pie"){
System.out.println("Hurrah!");
System.out.println("Hi!");
}

Also use .equals() for comparing rather than ==.

Solution 13 - Java

No, there is no difference between them with one statement in response to the if. If you want to add a second statement in response to the if, then curly braces are required.

Solution 14 - Java

It will work fine if there is only one statement after the if condition.

if("pie"== "pie")
    System.out.println("Hurrah!");
    System.out.println("second statement");// this will not print

but here both statement will print

if("pie"== "pie")
{
System.out.println("Hurrah!");
System.out.println("second statement");
}

I would suggest you to use like below even if you want to print single statement.

if("pie".equals("pie"))
   {
       System.out.println("Hurrah!");
       System.out.println("second statement");
   }

Solution 15 - Java

The curly braces is used only if you want to execute bunch of code in condition. If you do not use the braces then it will only execute first statement after if condition. The remaining lines (below the first statement) will not consider as a if part.

Solution 16 - Java

If you add curly braces to this if statement:

if(++colorIndex == someColors.length)
			colorIndex = 0;
		setForeground(currentColor());
		repaint();

Then it wont work anymore.

So i think in some cases it does matter.

Solution 17 - Java

If there's a single statement inside an if-then, the {} curly braces can be omitted. However, I tend to always include them as best coding practice since forgetting to use them with multiple statements inside an if-then will trigger an error.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser735977View Question on Stackoverflow
Solution 1 - JavaHabibView Answer on Stackoverflow
Solution 2 - JavaSergey KalinichenkoView Answer on Stackoverflow
Solution 3 - JavadrquicksilverView Answer on Stackoverflow
Solution 4 - Javakung_fu_coderView Answer on Stackoverflow
Solution 5 - JavaAniket IngeView Answer on Stackoverflow
Solution 6 - JavaThornView Answer on Stackoverflow
Solution 7 - JavarajeshView Answer on Stackoverflow
Solution 8 - JavaMiguel PrzView Answer on Stackoverflow
Solution 9 - Javamatt freakeView Answer on Stackoverflow
Solution 10 - JavaomikesView Answer on Stackoverflow
Solution 11 - JavaAndreas FesterView Answer on Stackoverflow
Solution 12 - JavaRaghunandanView Answer on Stackoverflow
Solution 13 - JavaBiswajitView Answer on Stackoverflow
Solution 14 - JavasubodhView Answer on Stackoverflow
Solution 15 - JavaShirish KulkarniView Answer on Stackoverflow
Solution 16 - JavaWim Van GeytView Answer on Stackoverflow
Solution 17 - JavaLv25_MagikarpView Answer on Stackoverflow