Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

If, Else IF

 
Vonique Leary
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!

Thanks for any help.

 
Ulf Dittmer
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
B. Bent
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Vonique Leary
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for all the replies. That clears things up for me nicely.

Von
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic