MathBits.com
Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use  

The "if ... else if ... else" Statements

Let's look at situations where your program requires more than two situations as the result of a decision.

int a = Console.readInt("Enter a value for a");
int b = Console.readInt("Enter a value for b");

if(a= = b)
{
     System.out.println("They are equal!\n");
}
else if( a < b)
{
     System.out.println("The first number is smaller.\n");
}
else
{
     System.out.println("The second number is smaller.\n");
}

 

Notice that it was not necessary to check for a>b.  The trichotomy principle tells us that numbers are related in one of three ways (a equals b, or a is less than b, or a is greater than b).  In order for the computer to get to the "else" condition in the problem above, it must have answered NO to the first two decisions.  Consequently, there is only ONE possibility left and we do not waste the computer's time checking it.

                


Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use