The following is a question from my teacher along with the correct answer:

public class IfTest {
        public static void main (String args[]) {
               if (true)
               if (false)
               System.out.println("a");
               else
               System.out.println("b");
       }
}

The code will compile correctly and display the letter b when run.

I have to explain why this is the correct answer. Is it because it skips both if statements since there is no condition and prints the else statement?

Recommended Answers

All 4 Replies

There are conditions. Simply trace them for yourself. Also, you should get in the habit of always using the braces around the statements following the conditional, even if it is a single statement.

What are you testing? With the statement if(true) and if(false) how can you tell where to go? I really don't understand this. I would get it if it said c=5, if (c>3) Print (Yes). else print (no). But there is no statement to test against these conditions. I'm lost.

It doesn't matter what you are testing so long as it evaluates to a boolean. If it's true then the statement is executed, otherwise the else{} portion is executed.

imaging ur code snippet was rewritten in this manner"

public class IfTest {
public static void main (String args[]) {
if (true)  {
if (false) {
System.out.println("a");
else{
System.out.println("b");
}
}
}

if you just don't have braces as in the if(true) case then its been accepted as the code/block of code in this case which is the whole of if(false) block belongs to the if(true) block.

even though these is no condition to be evaluated when stated as if(true) its results true
and simillary if(false) results as false.

so again the control first passes to the the if(true) block and results as true then goes in to the block and then comes if(false) which results to be false, which therefore executes the else statment printing the output as "b"

NOTE: the whole of if(false) block including its else is with in the if(true) block. remember the rule an ELSE always belong to the immediately above IF block.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.