Search code examples
javaif-statementcontrol-flowcurly-braces

If-Else Control Flow without curly braces


I am trying to run the below code with x =10 ."X is not equal to 10!" is getting printed. but As per documentation, the else belongs to the innermost if()? Also if we replace "1==2" in the if block with 1==1 then also "X is not equal to 10!" is getting printed. I have corrected the code ..
Edit : Got the answer.

   if(1==2)
        if(x!=10)
            System.out.println("X is equal to "+x);
       else
        System.out.println("X is not equal to 10!");

Solution

  • Indent correctly to see

    if(1==2)
        System.out.println(x);
    if(x!=10)
        System.out.println("X is equal to "+x);
    else
        System.out.println("X is not equal to 10!");
    

    I think that answers it already.
    But more detailed:

    First if is not true, the first println does not get executed (apart from the described second version).
    Second if is unconditionally evaluated, is not true, the else is executed.

    Or ot reflect it on the quote, there is no "inner" if because there is no if enclosing any other if.

    Or another aspect, you seem to think that the output is occurring because the first ifs condition is false, i.e. the else is attached to the first if. It is however attached to the second if because the conditional code influenced by the first if ends at the ;. To have more code influenced by the first if you could introduce a block of several lines, with a pair of {}.