0

I'm using the below free text to learn intro to java and I am having trouble understanding the difference between the code segments:

http://math.hws.edu/eck/cs124/downloads/javanotes7-linked.pdf

Example 1

    int x;
    x = -1;
    if (x < 0)
        x = 1;
    else
        x = 2;

Example 2

    int x;
    x = -1;
    if (x < 0)
        x = 1;
    if (x >= 0)
        x = 2;

In Example 1, x is 1; In Example 2, x is 2.

On the right, if -1 is not > or = to 0 then shouldn't the output be 1? Could someone please explain why the output would instead be 2?

6
  • on the left; program executes else block only if condition is false. so no need to explain right one its just executing lines in order. Commented Aug 12, 2016 at 18:50
  • This is a very basic question, please close it. Commented Aug 12, 2016 at 18:51
  • 4
    @ShivaShinde: What on earth is wrong with basic questions? Everyone starts with the basics. Commented Aug 12, 2016 at 18:52
  • Can someone send a mail to the author of that... thing. Is on the second page. Commented Aug 12, 2016 at 19:03
  • 2
    @JarrodRoberson or maybe DO use it. Because that code is there to explain why the code is bad. "The author is literally using it to address misconception or misunderstanding of new programmers about how if statements operate by saying that the two are not equivalent even if they can look the same to a new programmer. The author's point being (coincidentally) illustrated by OP being confused at what the difference would be. Commented Aug 12, 2016 at 19:14

3 Answers 3

5

Once the second if statement is evaluated, x the first has already taken effect--so the value of x is now 1.

if (x < 0)
   x = 1;


if (x >= 0) //x is 1 because you've already evaluated the above!
   x = 2;

The else keyword creates mutually exclusive branches: only one can be executed. So if you had this, the behavior would be as you expected:

if (x < 0)
   x = 1;
else if (x >= 0)
   x = 2;
Sign up to request clarification or add additional context in comments.

1 Comment

This answer is correct, @TheJuniorProgrammer... the second example contains two if statements.
2

In the Example 1, only one of the statements x = 1; or x = 2; will be executed because it uses an if...else statement.

In the Example 2, both statements will be executed because it uses two separate if statements, and because both conditions are true at the time they are evaluated.

Comments

0

In the second example; first you go through the first if condition:

x = -1;

if (x < 0) x = 1;

x is less than 0, so x becomes 1.

When you go to the second if condition:

if (x >= 0) x = 2;

x is still 1, and 1 is greater than 0, so x becomes 2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.