0
public class Main {
    public static void main(String[] args) {
        int x = 1;
        if (x < 10)
            if (x == 0)
                System.out.println("Zero");
            else if (x == 1)
                System.out.println("One");
            else
                System.out.println("Other but smaller than 10");
        else
            System.out.println("Greater than 10");
    }
}

I have just tried this and it worked exactly the same as if I surrounded the inner conditions with curly braces.
I know that it's possible to do one line statements with no curly braces, but why does it work in this case?

Thanks and I'm sorry if this is an obvious question.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
DZV31
  • 13
  • 2
  • 1
    Your issue is here: " one line statements" ... correct is "one statement", independent on the lines used. An if/else block with all its branches is one statement. – Tom Aug 18 '20 at 18:08
  • The inner stuff is really just one single block. I don't see why it shouldn't work – user Aug 18 '20 at 18:09
  • Similar, but with loops: [If an outer for loop has no braces, will an inner for loop be considered as a single statement?](//stackoverflow.com/q/27223859) – Tom Aug 18 '20 at 18:12
  • Your understanding is correct, and the only thing which you miss in your thinking is *how many statements are under each block?*. You actually have exactly **one** statement under each block of the `if-else` construction. Pay attention, that your parent **if**, has only one - nested **if** statement, and all the rest of `else` or `else if` blocks have similarly exactly *one statement* each. So, yes, if the `if-else` blocks don't have curly braces, they can contain one statement at most, and in your case, every block contains exactly one (*direct* connection, w/o grandchildren) statement. – Giorgi Tsiklauri Aug 18 '20 at 18:18

2 Answers2

0

It works because it can take a whole if-else block or another block. This would also work with a for loop for example:

for(String e : strArray) 
      if(e.equals(str)) 
            System.out.println("Yes);
      else...
JeroSquartini
  • 347
  • 1
  • 2
  • 11
0

This is working as expected because there is only one statement in each of the if, else-if and else block. It will fail if you try to put more than one statements in any of this block.

ab_
  • 377
  • 2
  • 5
  • 16