Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Can anyone please explain the difference between if/ else if and if/if ?

+3 votes
asked Oct 11, 2016 in CSC 211 (F16) by Tien Le (100 points)
It's also worth noting that when you have mutually exclusive conditions, it's often still better (more efficient) to use if/else if instead of just separate if statements. This will prevent the program from having to check all the possible conditions after it's found a true one.

4 Answers

+2 votes
If/else if basically ends as soon as the earlier statement is true.

For example,  this piece of codes

x = 10;
if ( x < 20) {
<do something 1>
} else if ( x < 40 ) {
<do something 2>
}

Only <do something 1> without even check the other else if.

In contrast,

x = 10;
if ( x < 20) {
<do something 1>
}
if ( x < 40 ) {
<do something 2>
}

Would do both <do something 1> and <do something 2> because x is both less than 20 and 40.
answered Oct 11, 2016 by Minh Ta (100 points)
+1 vote
With the IF/ELSE statement, the Java is gonna check if the "IF" statement first : if that statement is correct, its gonna run the statement and skip through the "ELSE" statement; otherwise, if the "IF" statement is false, its gonna run the "ELSE" statement.
With the IF/IF statement, Java runs both of them.
In conclusion, the IF/ELSE statement only gives 1 correct statement, and Java will run only 1 statement, and with the IF/IF statement, Java is gonna run both if both of the statements are correct
answered Oct 11, 2016 by Trung Le (Jayden) (100 points)
0 votes
To put it simply and briefly, and if/if statement will execute both statements, and run them through individually, even if the first is correct. An if/else statement will only execute one option, because it can't even attempt the other unless the first fails.
answered Oct 11, 2016 by Hunter Bader (100 points)
0 votes
I think the both kinds of conditionals have been defined so far, but for an example,

You would use an if/else for determining what the letter grade is in a program, so

if (grade >= 90) {

        grade = A

} else if (grade >= 80) {

        grade = B } ...           This would ensure that only one letter grade is assigned per interval. So, this would give only an A for the grade 95.

Using an if/if, you could assign multiple letter grades per interval, so

if (grade = 90 {

        grade = A

} if (grade >= 80) {

        grade = B } ...              This would give an A and a B for the value 95.\

Really, it depends on what you're trying to do with the program.
answered Oct 11, 2016 by Lars Harvey (100 points)
...