Timtim3 Timtim3 - 4 months ago 9
Java Question

'if - else' flow is confusing

I recently ran this program but the output is:

12
1
Three


I am curious about two things:
1. is the "System.out.println("Three")" included in the else clause?
2. Why is "Two" not printed?

Also, the code is missing brackets on purpose.

public class testttt {

public static void main(String[] args){
int w = 10;
int s = 21;
System.out.println(w+=2);
System.out.println(s % 10);
if ((s > 30) && true)
if (s / 2 > 10)
System.out.println("One");
else
System.out.println("Two");
System.out.println("Three");




}
}

Answer

Formatting the file correctly will help you understand it better.

public class testttt {

    public static void main(String[] args){
        int w = 10;
        int s = 21;
        System.out.println(w+=2);
        System.out.println(s % 10);
        if ((s > 30) && true)
            if (s / 2 > 10)
                System.out.println("One");
            else
                System.out.println("Two");
        System.out.println("Three");
    }
}

Because you're not using braces, only the first statement is used for each selection statement. The first if statement includes a single statement which consists of if AND else, and the else statement consists of only "Two".

Because the first if evaluates to false, only "Three" is printed because the else corresponds to the second if, not the first. The second if is never evaluated since the first fails, so else is never reached.