The Ternary Operator


x

Lesson:
Main Points:
  1. The ternary operator is often referred to as the conditional operator.
  2. It provides a way to code simple conditions (if/else) into a single expression.
  3. Some companies prohibit its use because they feel that it makes the resulting code less readable.
  4. It is a very concise way to code simple conditionals.

Basic Use of the Ternary Operator:
Here's a real simple example of the ternary operator in action:
String size = (x > 2) ? "BIG" : "SMALL"; In this case whatever value is stored in x will be compared to 2. If it is greater than two size will be assigned "BIG" and otherwise size will be assigned "SMALL" as its value. Here is the code for a very similar example:
import java.awt.*; import java.applet.*; public class tern extends Applet{ String num=""; int x[] = { 2, 22, 11, 8, 14, 15, 2, 9 }; public void init(){ setBackground(Color.yellow); } public void paint(Graphics g){ for(int c = 0; c<x.length; c++){ num = ( x[c]%2 == 0 ) ? "EVEN" : "ODD"; g.drawString(""+x[c] + " is " + num, 10, 20 + c*20); } } }

More Examples of the Ternary Operator In Action:
String ouput=""; output = ( a==10 || a == 20 ) ? "TEN or TWENTY" : "NOT 10 or 20"; // uses short-circuit logical OR operator String output=""; String name="Barney"; output = ( name.equals("Barney") ) ? "Dinosaur" : "Poodle" ; // uses String.equals function boolean short = true; int output = 0; output = short ? 100 : 200; //output assigned 100 since short is true
x

Assignment:
Write an applet which contains a list of names contained in an array of type String. Have at least eight names in your list. For each name determine if it is the name of a DORK or a NERD. At least three people on your list should be DORKs and at least three people on your list should be NERDs. Print out a little sentence like this for each person:
  Alvin is a DORK.

To create an String array you do the following:

String[] list = new String[]{ "one", "two", "three" };
x