The Conditional Operator

Things To Do Before Class

Things To Do After Class

The Conditional Operator

Once you know how to use conditions, 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, if 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

To use a conditional operator expression, 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

[Solutions]

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.".

Note
To find a random number between MIN and MAX, use the formula:
int randomNum = (int)(Math.random() * (max - min + 1) + min);
For example, to get a random number between 100 and 200:
int randomNum = (int)(Math.random() * (200 - 100 + 1) + 100);

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.