1
$\begingroup$

I am a beginner at Java and this code example came up in class:

int horsepower = 15;
      if(horsepower > 15)
         if(horsepower <= 20)
            System.out.println("There is a lot of horsepower");
      else
          System.out.println("The car super fast");

the output is nothing but I can't understand why.

I have 2 questions I would like to clarify:

  1. why did the code under the else statement not get executed?
  2. I understand that without the brackets { }, the if condition can only execute the next statement. In this case, if horsepower variable is 17 instead, will "There is a lot of horsepower." be printed ? I am unsure if the System.out.println("There is a lot of horsepower"); still qualifies as being part of the next statement of the first if condition.

Please advise. Thanks!

$\endgroup$
1
  • 1
    $\begingroup$ (Basically, because Java is not Python and any (non-empty/zero) amount of white-space equivalent: The else "belongs to" the 2nd if.) $\endgroup$
    – greybeard
    Commented Feb 3, 2021 at 18:13

1 Answer 1

3
$\begingroup$

Indentation has absolutely no syntactic or semantic meaning in Java, and indeed in most popular languages (the main exception is Python).

Which if does your else belong to? This is an instance of the famous dangling else problem. The syntax of Java associates each else to the innermost if, so the Java compiler understands your code in a way which is different than what your indentation suggests. If you want to associate the else with the outer if, you can use curly brackets.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.