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

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

System.out.println("Enter a value for a: ");
int a = reply.nextInt();
System.out.println("Enter a value for b: )";
int b = reply.nextInt();

if (a= = b)
     System.out.println("They are equal!\n");
else if ( a < b)
     System.out.println("The first number is smaller.\n");
     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 | | | Terms of Use  |