Using if-else statements, you can even select between three or more possibilities. Just add an else-if clause for each possibility after the if clause, and an else clause for the last possibility.
// 3-way choice with else-if
if (boolean-expression-1)
{
statement1;
}
else if (boolean-expression-2)
{
statement2;
}
else
{
statement3; // default action if none of the others are true
}
You can test the following code to see how an iif/elseif/else statement works. Change the value of x and see what happens.
Here is a flowchart that shows how else-if statements control the flow of the program.
If you want to compare objects, including Strings, you MUST use the object’s method called, equals(). s1.equals(s2)
returns true if s1 and s2 have all the same characters in the same order.
With Strings and other objects, == will NOT work correctly in all instances. See the code below and find out.