Java
TOPIC 15 – IF STATEMENTS – PART 2

AP EXTRA

 

 

AP LESSON NOTE

 

 

TERNARY OPERATOR

 

Java has a strange operator that can replace simple IF statements.  It's called the ternary operator or the conditional operator.  It is a little weird to read and some programmers avoid using it for that reason.  But it can be used to do some neat things on a single line.

 

EXAMPLE


Let's assume that variable x and y are both integers and have both been initialized.  Here is an example with the ternary operator in use:


         int minValue = (x < y) ? x : y;

 

EXPLANATION

 

If the condition is true, then minValue will get x.  If the condition is false, minValue will get y.  So, minValue will get the smaller of the two values.  This is a way to replace the min function from the Math class.

 

EXAMPLE 2

 

Assume variable v is an integer that has been initialized.

 

         int absoluteValue = (a < 0) ? -a : a;

 

EXPLANATION

 

If the condition is true, then absoluteValue gets the first value –a.  Otherwise, absoluteValue gets the value a.  Overall, the variable absoluteValue

 

EXAMPLE 3

 

Assume the variable cash has been initialized.  We can use the ternary operator to output one of two words to get correct spelling.

 

         System.out.println("You have " + cash + (cash == 1) ? "dollar." : "dollars.");

 

EXPLANATION

 

If cash is equal to 1, then we output "dollar".  Otherwise we output "dollars".   It's pretty cool.  And yet, you can probably see how this can get messy and hard to ready.

 

EXAMPLE 4 – NESTING MULTIPLE OPERATORS

One can include multiple operators inside one another.  Assume the variable amount is an integer and has been initialized.

 

          String result = (amount <= 2) ? "couple" : (amount < 5) ? "few" : (amount <= 8) ? "several" : "many";

 

EXPLANATION

 

The above line gives result a worded description that corresponds to the value in amount.