Overview of This Lesson

You've already learned about several binary operators in Java: +, -, *, /, and %, for example. Binary operators have 2 operands (a value on the left of the operator and a value on the right of the operator). Unary operators such as ++ and -- have a single operand. The ternary operator ?: has 3 operands: operand1 ? operand2 : operand3

The ternary operator, also called the conditional operator, allows you to write a single expression that evaluates a relational expression and returns one result if the expression is true, and a different result if the expression is false. It's a helpful operator to use when you want to get a value based on a specific condition.

Pre-Requisites

Before doing this tutorial, make sure you've gone through the lesson on relational and logical expressions.

The Conditional Operator

Once you know how to use relational expressions, you can use the conditional operator. The conditional operator allows you to code a simple decision that can result in one of two actions. For example, with a conditional operator you can check the value of a variable to see if it's larger than 100. If it is, you can display a message on the console. If it isn't, you can display a different message.

The conditional operator is the ? symbol. It's actually a ternary operator - it requires three operands (binary operators require 2 operands, unary operators require 1 operand). The general format of the conditional is as follows:

(conditionalExpression) ? valueIfTrue : valueIfFalse

The conditionalExpression is an expression that evaluates to a boolean value of true or false. A typical conditional expression uses one of the binary relational operators (<, <=, >, >=, == (equals), != (not equals)) with an operand on either side. For example, assume x=10, y=5, and z=20:

x > y - evaluates to true
z >= 20 - evaluates to true
x * y < z - evaluates to false
x + y >= z - evaluates to false

Keep in mind that the conditional expression must appear in parentheses and it must always have a boolean (true or false) result.

The valueIfTrue is the value that the operator returns if the conditional expression evaluates to true, and the valueIfFalse is the value that the operator returns if the conditional expression evaluates to false. Remember, this is an operator, so like any other operator (*, +, <) there is a result. With a conditional operator, the 2nd and 3rd operands are the two possible results that this operator could return. Examples (assume z = 50):

(x * x >= 0) ? 10 : 20      // returns the integer value 10
(z >= 20) ? "yes" : "no"    // returns the string "yes" 
(z < 20) ? 10.5 : 25.0      // returns the double value 25.0

Like any other expression, a conditional expression returns a value, so you must make sure that you are using the expression's result, or storing it somewhere. If you are putting the return value in a variable, you must make sure that the variable's data type matches the type of the 2nd and 3rd operands. For example:

String discount = (age >= 65) ? "discount of 5%" : "no discount";
double discount = (age >= 65) ? .05 : 0.0;
int discount = (age >= 65) ? 5 : 0;

Exercises

1. The method Math.random() generates a random double number greater than 0.0 and less than 1.0. Write a program that simulates flipping a coin. Call the Math.random() method and if the number generated is less than .5, display "HEADS". Otherwise, display "TAILS".

2. To generate a random integer value, you have to modify the result returned by Math.random(). For example, to generate a random number between 1 and 10, you would do this:

double randomNum = Math.random();  // gets a random double
randomNum *= 10;                  // moves the decimal over 1 spot
int randomInt = (int)randomNum;   // chops off the decimal part

// now we have a number from 0 to 9, so add 1 to make it 1 to 10
randomInt++;

Of course, most people find it easier to simply do this:

int randomNum = (int)(Math.random() * 10) + 1;

Write a program that generates a random integer from 1 to 5. Then ask the user to guess that number. If they guess correctly, display the message, "You guessed correctly!". If they guess incorrectly, display the message, "Sorry, you guessed incorrectly.".

3. Write a program that simulates the tossing of two dice (generate two random integers from 1 to 6). If doubles are rolled, display a "You Win!!" message. Otherwise, tell the user what dice values they rolled.

4. Second Life's breedable KittyCatS!™ can breed out kittens when they're under 121 days in age. Kittens can't breed, so a cat can't breed out kittens until it's 14 days old. Write a program that prompts the user for the age of the cat in days and displays either "Breedable: ON" (if the cat is of breedable age) or "Breedable: OFF" (if the cat is not of breedable age.

5. A program prompts the user to enter a department number. A valid department number is:

Display whether a user-entered department number is "valid" or "invalid". Use a single conditional statement.

1.

code solution 1
Question 1. heads or tails

2.

code solution 2
Question 2. guess a number

3.

code solution 3
Question 3. rolling dice

4.

code solution 4
Question 4. breedable pixel cats

5.

code solution 5
Question 5. valid/invalid department number