Or Else ... |
Now
ifis all very well, but sometimes we want to do two things; do one thing if something is true and another thing if it is false. Take this example:
class Hello { public static void main(String[] args) { int x = 4, y = 5; System.out.println("What's that you say? x equals y?"); System.out.println("Hmm, well if x is " + x + " and y is " + y + "..."); } }We've not used any
ifs yet, but we will, trust me. Now let's explain the program. We've used another bit of shorthand in the first statement - we've created two variables (xandy) and given them both values (x = 4andy = 5). We can do this with any number of variables provided we separate them with commas.The second statement just prints out a message to the screen. The third one prints out the values of
xandy, whatever they might be. Let's see:
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello What's that you say? x equals y? Hmm, well if x is 4 and y is 5... [nurmes]btg:Was that what you were expecting? We've used the
+operator several times to add together lots of strings and integers. Count 'em - there's three strings ("Hmm, well if x is "is one," and y is "is another and"..."is the third) and two integers (xandy).So let's add some iffy stuff.
class Hello { public static void main(String[] args) { int x = 4, y = 5; System.out.println("What's that you say? x equals y?"); System.out.println("Hmm, well if x is " + x + " and y is " + y + "..."); if (x == y) System.out.println("Gosh, that's true!"); if (x != y) System.out.println("No, I don't believe you!"); } }And see what happens:
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello What's that you say? x equals y? Hmm, well if x is 4 and y is 5... No, I don't believe you! [nurmes]btg:Surprisingly, the computer isn't fooled - four does not equal five. Change the program slightly:
class Hello { public static void main(String[] args) { int x = 4, y = 4; System.out.println("What's that you say? x equals y?"); System.out.println("Hmm, well if x is " + x + " and y is " + y + "..."); if (x == y) System.out.println("Gosh, that's true!"); if (x != y) System.out.println("No, I don't believe you!"); } }
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello What's that you say? x equals y? Hmm, well if x is 4 and y is 4... Gosh, that's true! [nurmes]btg:And now it's a lot happier. Four does equal four. I hope that you can understand what is going on but I suppose you can't really see the point. I'll explain.
Look at the two
ifstatements in the program. One is testing to see ifx == yis true, and the other to see ifx != yis true. So obviously if one of these is true then the other is false; either they are equal or they aren't.In fact this was just what I meant it to do. Now I'm going to show you an easier way to achieve the same result using our new friend
else.
class Hello { public static void main(String[] args) { int x = 4, y = 4; System.out.println("What's that you say? x equals y?"); System.out.println("Hmm, well if x is " + x + " and y is " + y + "..."); if (x == y) System.out.println("Gosh, that's true!"); else System.out.println("No, I don't believe you!"); } }Notice that we've changed the line
if (x != y)to simplyelse. The way theelsestatement works is, if the condition (which we called earlier the "yes/no question") is true then it executes the statement directly after theif, and if the condition is false then it executes the statement directly after theelse. Since the condition can only be true or false, it never executes both. You'll see:
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello What's that you say? x equals y? Hmm, well if x is 4 and y is 4... Gosh, that's true! [nurmes]btg:Exactly as before. Because
x == yis true, the statement afterelsenever gets executed. Change the value ofyback to5so thatx == yis false:
class Hello { public static void main(String[] args) { int x = 4, y = 5; System.out.println("What's that you say? x equals y?"); System.out.println("Hmm, well if x is " + x + " and y is " + y + "..."); if (x == y) System.out.println("Gosh, that's true!"); else System.out.println("No, I don't believe you!"); } }See if you can work out what's going to happen before you try it.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello What's that you say? x equals y? Hmm, well if x is 4 and y is 5... No, I don't believe you! [nurmes]btg:This is just like the last time when
ywas5. Look:
Using two ifstatementsUsing an ifstatement and anelsestatementif (x == y) System.out.println("Gosh, that's true!"); if (x != y) System.out.println("No, I don't believe you!");if (x == y) System.out.println("Gosh, that's true!"); else System.out.println("No, I don't believe you!"); [nurmes]btg: javac Hello.java [nurmes]btg: java Hello What's that you say? x equals y? Hmm, well if x is 4 and y is 5... No, I don't believe you! [nurmes]btg: [nurmes]btg: javac Hello.java [nurmes]btg: java Hello What's that you say? x equals y? Hmm, well if x is 4 and y is 5... No, I don't believe you! [nurmes]btg:Now let's compare the two approaches when
yis4:
Using two ifstatementsUsing an ifstatement and anelsestatementif (x == y) System.out.println("Gosh, that's true!"); if (x != y) System.out.println("No, I don't believe you!");if (x == y) System.out.println("Gosh, that's true!"); else System.out.println("No, I don't believe you!"); [nurmes]btg: javac Hello.java [nurmes]btg: java Hello What's that you say? x equals y? Hmm, well if x is 4 and y is 4... Gosh, that's true! [nurmes]btg: [nurmes]btg: javac Hello.java [nurmes]btg: java Hello What's that you say? x equals y? Hmm, well if x is 4 and y is 4... Gosh, that's true! [nurmes]btg:I'm hoping that this helps you to grasp exactly what
ifandelsedo. Maybe you still can't see the point. Well one point is that you only need to write the condition once. It might not seem like a big deal with these simple examples. How about this - which of the following would you prefer to type in?
if (x == y || (x % 6 == 2 && y / 4 == 0)) System.out.println("Gosh, that's true!"); if (!(x == y || (x % 6 == 2 && y / 4 == 0))) System.out.println("No, I don't believe you!");if (x == y || (x % 6 == 2 && y / 4 == 0)) System.out.println("Gosh, that's true!"); else System.out.println("No, I don't believe you!");While they are exactly equivalent, I think you'll agree that the version with the
elseis far simpler to read. Also it only works out the condition once, which makes the program run faster. Again, in these examples speed is not significant, but in a Maffematical Algowythm when thisifis executed millions of times, it would matter. If you're still not clear on what condition means, then in this example the condition isx == y || (x % 6 == 2 && y / 4 == 0). In the previous example it was justx == y.Now we are going to be using more than one
elseat a time. If you understand this lesson, your life will be better (as the song goes). Here's a new (and exciting?!?!?) program to try:
class Hello { public static void main(String[] args) { int x = 2; System.out.println("Let's see if x is positive or negative."); if (x > 0) System.out.println("It appears to be positive, Miss Moneypenny."); else System.out.println("Now pay attention, Bond. Agent X is negative."); } }By now I expect you to be able to understand what this program does without me explaining it.
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Let's see if x is positive or negative. It appears to be positive, Miss Moneypenny. [nurmes]btg:Now change the value of
xto-3...
class Hello { public static void main(String[] args) { int x = -3; System.out.println("Let's see if x is positive or negative."); if (x > 0) System.out.println("It appears to be positive, Miss Moneypenny."); else System.out.println("Now pay attention, Bond. Agent X is negative."); } }...and the statement after the
elseis executed:
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Let's see if x is positive or negative. Now pay attention, Bond. Agent X is negative. [nurmes]btg:Here's a problem:
class Hello { public static void main(String[] args) { int x = 0; System.out.println("Let's see if x is positive or negative."); if (x > 0) System.out.println("It appears to be positive, Miss Moneypenny."); else System.out.println("Now pay attention, Bond. Agent X is negative."); } }So you've changed
xto zero and...
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Let's see if x is positive or negative. Now pay attention, Bond. Agent X is negative. [nurmes]btg:It's not really right, is it? The cases where
xis any positive or negative number work fine (you can try some more if you don't believe me). But I think that's avoiding the issue. What we really need to do is check for a negative number too. If it's not negative, then we can print out a message to say it's zero. Let's do it:
class Hello { public static void main(String[] args) { int x = 0; System.out.println("Let's see if x is positive or negative."); if (x > 0) System.out.println("It appears to be positive, Miss Moneypenny."); if (x < 0) System.out.println("Now pay attention, Bond. Agent X is negative."); else System.out.println("Actually sir, I think it's zero."); } }
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Let's see if x is positive or negative. Actually sir, I think it's zero. [nurmes]btg:Well that seems straightforward. Unfortunately it doesn't work properly for positive values of
xany more:
class Hello { public static void main(String[] args) { int x = 2; System.out.println("Let's see if x is positive or negative."); if (x > 0) System.out.println("It appears to be positive, Miss Moneypenny."); if (x < 0) System.out.println("Now pay attention, Bond. Agent X is negative."); else System.out.println("Actually sir, I think it's zero."); } }
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Let's see if x is positive or negative. It appears to be positive, Miss Moneypenny. Actually sir, I think it's zero. [nurmes]btg:Well it seems that they can't agree. Obviously we know that
xis zero, but we really want to print this without saying that it's positive. The basic problem is that we only want to execute theif (x < 0)statement if we haven't already printed thatxis positive. Look at this:
class Hello { public static void main(String[] args) { int x = 2; System.out.println("Let's see if x is positive or negative."); if (x > 0) System.out.println("It appears to be positive, Miss Moneypenny."); else if (x < 0) System.out.println("Now pay attention, Bond. Agent X is negative."); else System.out.println("Actually sir, I think it's zero."); } }
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Let's see if x is positive or negative. It appears to be positive, Miss Moneypenny. [nurmes]btg:If we change the value of
xto-3(I'm not going to do it for you, you can do that yourself by now) then it still works:
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Let's see if x is positive or negative. Now pay attention, Bond. Agent X is negative. [nurmes]btg:And finally, if we try it with
x = 0:
[nurmes]btg: javac Hello.java [nurmes]btg: java Hello Let's see if x is positive or negative. Actually sir, I think it's zero. [nurmes]btg:Which is just diddly-doo-dah fine, but how the Jeffrey Archer does it all work?
Well, what we've done (in effect) is written the second
ifinside theelsebelonging to the firstif. Unfortunately the secondifalso has its ownelse(that's the second one in the program). I've written it in a way which perhaps makes it easy to see what it does, but harder to understand exactly how it does it. I really want you to understand exactly how as well. So we're going to rewrite it slightly to make it 100% clear how everything works. Once again, we're going to use the power of indenting (get ready with that tab key - and enter).
class Hello { public static void main(String[] args) { int x = 2; System.out.println("Let's see if x is positive or negative."); if (x > 0) System.out.println("It appears to be positive, Miss Moneypenny."); else if (x < 0) System.out.println("Now pay attention, Bond. Agent X is negative."); else System.out.println("Actually sir, I think it's zero."); } }Remember that whitespace (that's tabs, spaces and new lines) makes no difference at all to how the program works. However it can make a difference to how we understand it.
To show what happens I've highlighted in blue the bits of the program which are actually executed in each case.
Value of xis positiveclass Hello { public static void main(String[] args) { int x = 2; System.out.println("Let's see if x is positive or negative."); if (x > 0) System.out.println("It appears to be positive, Miss Moneypenny."); else if (x < 0) System.out.println("Now pay attention, Bond. Agent X is negative."); else System.out.println("Actually sir, I think it's zero."); } }See above that the parts after the first
elsenever even get touched.
Value of xis negativeclass Hello { public static void main(String[] args) { int x = -3; System.out.println("Let's see if x is positive or negative."); if (x > 0) System.out.println("It appears to be positive, Miss Moneypenny."); else if (x < 0) System.out.println("Now pay attention, Bond. Agent X is negative."); else System.out.println("Actually sir, I think it's zero."); } }Now in the case above, the computer looks at the first
if. But the condition (x > 0) evaluates to false (I'm not losing you in the jargon I hope). So we go on to execute the statement after the firstelse(the firstelsematches the firstif). This statement just happens to be anotherif-else. Note that the four lines
if (x < 0) System.out.println("Now pay attention, Bond. Agent X is negative."); else System.out.println("Actually sir, I think it's zero.");are considered as one statement - in fact, they are the "one statement" following the first else. After we get to here we evaluate the condition
x < 0. This condition is true sincexis-3. So we execute the statement after thisif(printing the message "Now pay attention, Bond. Agent X is negative.") and ignore the secondelse. It's probably clearer from the colouring.
Value of xis zeroclass Hello { public static void main(String[] args) { int x = 0; System.out.println("Let's see if x is positive or negative."); if (x > 0) System.out.println("It appears to be positive, Miss Moneypenny."); else if (x < 0) System.out.println("Now pay attention, Bond. Agent X is negative."); else System.out.println("Actually sir, I think it's zero."); } }Let's explain this one in the style of someone in a hurry: We see if
x > 0and it isn't, so we see ifx < 0and it isn't that either, so it must be zero.That's more than enough explaining! If you really still don't get it, ask a human being. Now I'm going to add some curly brackets to the program. Remember that we do this to define a block, when we want to have more than one statement after an if or and else. We don't need to do this in my example, but you probably will in most programs you write containing an
if-else. Think of it as a lesson in laying programs out neatly. If you do all yourif-elsestatements like this then you will not only find it easier to understand your programs, but your tutor will too and you'll probably get better marks.
class Hello { public static void main(String[] args) { int x = 0; System.out.println("Let's see if x is positive or negative."); if (x > 0) { System.out.println("It appears to be positive, Miss Moneypenny."); } else { if (x < 0) { System.out.println("Now pay attention, Bond. Agent X is negative."); } else { System.out.println("Actually sir, I think it's zero."); } } } }Now we have four shades of curly brackets, to show which ones match up with which in case you were in any doubt. I really hope you can see them all. If you can't, try adjusting the contrast on your monitor. If you still can't, complain to me about it.
class Hello { public static void main(String[] args) { int x = 0; System.out.println("Let's see if x is positive or negative."); if (x > 0) { System.out.println("It appears to be positive, Miss Moneypenny."); } else { if (x < 0) { System.out.println("Now pay attention, Bond. Agent X is negative."); } else { System.out.println("Actually sir, I think it's zero."); } } } }Alternatively, we can set out our
if-elsestatements as follows (we did something like this before):
class Hello { public static void main(String[] args) { int x = 0; System.out.println("Let's see if x is positive or negative."); if (x > 0) { System.out.println("It appears to be positive, Miss Moneypenny."); } else if (x < 0) { System.out.println("Now pay attention, Bond. Agent X is negative."); } else { System.out.println("Actually sir, I think it's zero."); } } }We're most likely to do this when testing for a number of different values of
x:
class Hello { public static void main(String[] args) { int x = 0; System.out.println("Let's see if x is positive or negative."); if (x == 007) { System.out.println("The name's Bond. James Bond."); } else if (x == 99) { System.out.println("Faschinating."); } else if (x > 0) { System.out.println("It appears to be positive, Miss Moneypenny."); } else if (x < 0) { System.out.println("Now pay attention, Bond. Agent X is negative."); } else { System.out.println("Actually sir, I think it's zero."); } } }I don't intend you to run this program, it's just an illustration. Anyhow, this last lesson is finally over (it's taken me far longer to write it than it took you to read it). Next we're learning How to Type.
Too patronising? Too complex? Typing error? Offended by traffic cones?
Got a question or something I should add? Send an email to ben_golding@yahoo.co.uk !
visits to this site
The contents of this site are copyright of Ben Golding