1
votes

I'm a newbie in the world of Java and currently learning IF statements.

In the text-book I'm currently using, it is asking me to 'rewrite the following nested if statements without using any nesting'.

Now, I have two questions. The first one is in regards to whether or not I'm reading this in the right sequential order and the second one on whether there is a conflicting condition in lines 1 and 2 (a paradox). The problem question they ask me to rewrite is the following:

if ( a < b )
   if (a >= b)
       x = z;
   else
       x = y;

else
  x = z;

To my limited understanding of if statements, the sequential order would probably be the following:

  1. if variable a is less than b then execute the first statement (which is another if statement) and execute the SECOND else statement if the condition is false.
  2. if variable a is equal to or greater than b then execute the accompanying statement or if the condition is false then execute the FIRST else statement.

Am I reading this correctly so far? I apologise if I am making things hard to understand.

Now onto the second question; if the first if statement comes out as true (a being less than b) how can a be potentially greater than or equal to b when the first condition is already true? Wouldn't that be conflicting?

Thanks for helping :)

2

2 Answers

0
votes

You understand it right.

The code is actually equivalent to:

if (a < b)
    x=y;
else
    x=z;

If a < b, than for sure (a >= b) is false, and you go to the first else statement. If not - the statement in the second else is ran.

This is true almost for every language and every variable type, but might not be true in some cases, if you overloaded the operators inconsistently. Another case, is if you implement the operator a < b, such that it will change the value of a. However, such cases should not exist in normal code.

0
votes

Following the logic of the code you posted, it is equivalent to:

if (a < b)
    x = y;
else
    x = z;