What is the difference between If and Else If commands? I understand that in the Else If, the Else is only executed if the original IF does not evaluate to true, but in the following code, what would the difference be? In the three consecutive IF clauses, there is only one that can be executed anyway since the user only gets to put in one choice, so would an Else If work here just as well? And would a plan IF have worked in the Else IF's?
The following code is from John Smiley's book, Learn to Program In Java. Great book by the way. Just love it!
The following two code sections are not identical. In the first case, at most one of the code blocks is executed, but possible none:
In the following case, it's possible that all 3 of the code blocks are executed, but possible none:
In your particular case this wouldn't make a difference as long as the conditions all test for non-overlapping conditions (which they seem to at a quick glance); but in general, there is a difference between these two.
In this example condition_1 will be checked and if it's true the Code_1 will be executed.
condition_2 and 3 will NOT be checked and Code_2 and 3 will NOT be executed.
IF condition_1 is false condition_2 will be checked. If it's true Code_2 will be executed, And code_3 will not.
And if condition_1 and 2 is false, condition_3 will be checked. True and Code_ 3 will be executed. If false nothing will be executed.
In this code condition_1 will be checked. If true code_1 will be executed, if false he will not be executed.
Then condition_2 will be checked. If true code_2 will be executed, if false he will not be executed.
Then condition_3 will be checked. If true code_3 will be executed, if false...
So in first code you have ONE if-else construction, and in second you have THREE independent constructions.
It's complicated when I use english, sorry.
Joined: Mar 24, 2008
Thanks for all the replies. That clears things up for me nicely.