The "else if" statement, or "cascading if statements" are often used when a switch statement seems to be called for, but just wouldn't quite work. For example, let's say you wanted to write some code that printed the English translation of three different French words. If the user enters "un", our program should print "one". If the user enters "deux", it should print "two", and if "trois", should print "three". Otherwise our program should print a statement indicating that it cannot translate the phrase.
One way to solve this would be to use a switch statement.
Suppose the String s
contains the string the user entered. We might
try
String answer; switch (s) { case "un": answer = "one"; break; case "deux": answer = "two"; break; case "trois": answer = "three"; break; default: answer = "I can't translate that phrase."; } System.out.println(answer);
Another way to solve this is to use "else if" statements. Now, there's really no such thing as an "else if" statement. The term refers only to a particular use of if else statements and the way in which they are formatted. This is also sometimes referred to as "cascading ifs". (See pg. 218 for another description.) Here's the way I would solve this problem using "else if":
String answer; if (s.equals("un") answer = "one"; else if (s.equals("deux")) answer = "two"; else if (s.equals("trois") answer = "three"; else answer = "I can't translate that phrase."; } System.out.println(answer);