A replacement for the if / else statement in assignment.
The most nifty move you can pull. Use it and other coders will give you a knowing nod in the street. You will be the Jackie Chan Kung Fu King/Queen of Code.
How do I pull this amazing move?
variable = condition?expression1:expression2;
If the condition is true, expression1 is used, otherwise expression2 is used.
Ternary example
name = (fileFound==true)?(filename):(defaultName);
...is the same as...
if (fileFound==true) {
name = filename;
} else {
name = defaultName;
}
Why use it?
Because we can... just because we can.
if / else / if ladder
For more complex statements with multiple choices.
if (condition)
statement or {statements;}
else if (condition)
statement or {statements;}
else if (condition)
statement or {statements;}
else
statement or {statements;}
You need to put the elements with the most chance of being true
at the top, otherwise it is very inefficient.
Switch
switch (variable) {
case value1:
statements1;
break;
case value2:
statements2;
break;
case value3:
statements3;
break;
default:
statements4;
}
Slightly slower, but not as slow as a bad if-else-if ladder.
The break's are optional, if you leave one out, the computer will just run on into the next values case statements.
int day = 7;
switch (day) {
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Meh, whatever");
}
Note that unlike the 'if / else if / else' ladder the conditions generally have to be fixed; they can't be variables (this changed with Java 7, but many people have JRE 6).
Review
if (some condition) {
do something;
} else {
do something else;
}