aspose file tools*
The moose likes Beginning Java and the fly likes If, Else IF Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "If, Else IF" Watch "If, Else IF" New topic
Author

If, Else IF

Vonique Leary
Ranch Hand

Joined: Mar 24, 2008
Posts: 107
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
Marshal

Joined: Mar 22, 2005
Posts: 42289
    
  64
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.


Ping & DNS - my free Android networking tools app
B. Bent
Greenhorn

Joined: Jun 05, 2009
Posts: 5
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

Joined: Mar 24, 2008
Posts: 107
Thanks for all the replies. That clears things up for me nicely.

Von
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: If, Else IF