54

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.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • 27
    Do not compare strings with `==` in Java; always use `.equals()`. – Jesper Apr 03 '13 at 12:10
  • 8
    To amaze you more, you can write all of that on the same line too! – Azmi Kamis Apr 03 '13 at 12:11
  • @Jesper Right! I just learned that a while ago and completely forgot! –  Apr 03 '13 at 12:12
  • 21
    I'm curious about the downvotes. Seems a sensible question for someone learning programming/Java – matt freake Apr 03 '13 at 12:14
  • 8
    I think there are a lot of people who downvote because they think a Question is "too easy" / "too obvious" ... forgetting that they were once beginners too. But 1 upvote == 5 downvotes in terms of reputation. – Stephen C Apr 03 '13 at 12:24
  • 1
    @StephenC I agry with your first point, but your second point seems to be confusing to me. How `1 upvote == 5 downvotes`?(on a question) I think `1 upvote == 5 reputation` and `5 downvotes== -10 reputation` – Bhushan Apr 03 '13 at 12:36
  • 1
    @Bhushan - 1) Why are you angry with my point? I'm just saying why I think they do it. I didn't say that I agree with them. (I don't. Isn't it obvious from what I wrote??). 2) Yea, my mistake. 1 upvote == 2.5 downvotes. But the OP is **way ahead** on rep points. – Stephen C Apr 03 '13 at 13:57
  • @StephenC hey Stephen you miss read my sentence, I said `AGRY with your first point`, I didn't said `ANGRY` – Bhushan Apr 04 '13 at 04:00
  • 3
    @Bhushan I think you mean "Agree" Instead of "agry"? –  Apr 04 '13 at 05:49
  • 2
    @Bhushan - I only misread it because you miswrote it. Agry is not an English word, and to a native English speaker (like me) "agry" is a typo for "angry" not a misspelling of "agree". (The "y" in "agry" would be a short E, but "ee" in "agree" is a long E. Though admittedly English pronunciation rules are very inconsistent.) – Stephen C Apr 04 '13 at 07:09
  • @Firetryer yes I mean `Agree` – Bhushan Apr 04 '13 at 08:22
  • By the way, Java and Javascript are very different, but this question is valid for both! – corn on the cob Sep 14 '20 at 17:11

17 Answers17

50

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

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)

Makoto
  • 104,088
  • 27
  • 192
  • 230
Habib
  • 219,104
  • 29
  • 407
  • 436
  • 3
    Anyway it is a VERY good practice to ALWAYS use the braces. Have a look at https://www.imperialviolet.org/2014/02/22/applebug.html for some evidence (although it is in C, it does not really matter in this case) – MrTJ Mar 05 '14 at 14:59
  • the code in that link does not show an error caused by missing braces. it shows a person who left the same line in twice. this could have occurred whether the braces were there or not. – omikes Feb 07 '18 at 20:09
7

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
5

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.

drquicksilver
  • 1,627
  • 9
  • 12
5

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.

kung_fu_coder
  • 146
  • 2
  • 3
4

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.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
3

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);
Thorn
  • 4,015
  • 4
  • 23
  • 42
  • Another disadvantage is the problem of the [dangling else](https://www.cs.umd.edu/~clin/MoreJava/ControlFlow/dangling.html) in cases of nested conditionals. – GStav Mar 08 '17 at 23:57
2

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

rajesh
  • 3,247
  • 5
  • 31
  • 56
2

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

Miguel Prz
  • 13,718
  • 29
  • 42
2

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.

matt freake
  • 4,877
  • 4
  • 27
  • 56
1

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.

omikes
  • 8,064
  • 8
  • 37
  • 50
0

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.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
0

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 ==.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0

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.

gaige
  • 17,263
  • 6
  • 57
  • 68
Biswajit
  • 2,434
  • 2
  • 28
  • 35
0

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");
   }
subodh
  • 6,136
  • 12
  • 51
  • 73
  • The first example you wrote is wrong. `"second statement"` will be printed unconditionally, i.e. it will *always* be printed. – dingalapadum Mar 12 '17 at 14:03
0

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.

0

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.

-1

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.

  • 2
    This is what almost every other answer here is saying. Except for the "trigger an error" part, which is not entirely accurate. The other statements will just be executed. There's no guarantee that they will or will not trigger an error. – Scratte Apr 12 '20 at 14:50