-6
3: int temperature = 4;
4: long humidity = -temperature + temperature * 3;
5: if (temperature >= 4)
6: if (humidity < 6) System.out.println("Too Low");
7: else System.out.println("Just Right");
8: else System.out.println("Too High");

The above is a question from the Oracle Java OCP Study Guide chapter 4, question 2.

The answer says that this prints "Just Right".

The book tells us that control flow statements such as "if" require curly braces if there are multiple statements in that conditional branch.

Is the nested if-else statement considered a single statement or multiple statements?

Tom Spencer
  • 34
  • 1
  • 4
  • 3
    [Please do not upload images of code/errors when asking a question.](//meta.stackoverflow.com/q/285551) – Ivar Dec 22 '21 at 17:30
  • Also check other questions like https://stackoverflow.com/questions/31591196/java-if-statements-without-brackets-creates-unexpected-behaviour – Progman Dec 22 '21 at 17:31
  • You don't need curly brackets if there is only one statement to be executed, in this case line 5 only considers line 6 but that only considers line 7 so they flow into each other. – Alias Cartellano Dec 22 '21 at 17:35
  • In simpler terms, without braces (`{` and `}`), the `if` statement will only run code up to the next semicolon `;` – Rogue Dec 22 '21 at 17:35

1 Answers1

1

The book is correct in saying that you need curly braces if the if() statement should control multiple statements. However, in this particular code, the two lines

if (humidity < 6) System.out.println("Too Low");
else System.out.println("Just Right");

are actually one single complete if-else statement. So the "outer" if statement

if (temperature >= 4)

is controlling the "inner" if statement from above.

The number of lines the code is written in does not matter on when curly braces are required or not, only the number of statements it should control matters. When you have the following code

if (someCondition)
    System.
        out.println(
    "Just Right"
        )
    ;

the number of lines this if() statement is controlling is five, however, it is still one simple complete "method invocation" statement, just spanning over several lines, so no curly braces needed.

Progman
  • 16,827
  • 6
  • 33
  • 48
  • This is helpful. Particularly your point regarding ```if (humidity < 6) System.out.println("Too Low"); else System.out.println("Just Right");``` being one statement as opposed to multiple statements. – Tom Spencer Dec 22 '21 at 21:37