I just wanted to know if there is any purpose to writing else if or if this is purely written for better code readability. For instance, this code taken from the oracle java tutorials:
class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
surely writing the "else if" parts with just if would do that same thing? If anyone can help explain this to me I would greatly appreciate it. Thanks
It's mostly about performance but also about what you want to express! Imagine the testscore is >= 90 then the grade variable would be set to 'A' and no other if statements would be evaluated.
Rewriting the code to
would also check if the testscore is >= 80 and set the grade to 'B', then check for >= 70 and set it to 'C', etc...
So in your example, not only would you get the wrong result, you would also do a lot more checks!