Microsoft Word Document

foreheadsobstinacySoftware and s/w Development

Aug 15, 2012 (5 years and 2 days ago)

238 views

Programming in Java with NetBeans

Using the Ternary Operator in java

The
ternary

operator is another way of doing a conditional structure in java. An
if

statement or a
switch

statement are examples of conditional structures in java. The best
way to demonst
rate is by creating an
if

and then converting it into
ternary
.



If

If(skillLevel>5){

numberOfEnemies = 10;

}else{

numberOfEnemies = 5;

}
1



Ternary

numberOfEnemies =(skillLevel > 5) ? 10: 5;


So the ternary operator is obviously the
?
. It is used above wi
th a condition (skillLevel
>5) and the value if the condition is true is 10 and if not then the value is 5.


You will find a similar thing used in excel in combination with the if. In excel the entire
if is on one line A12= if(s10>5, 10,5) Here I am using

a cell location instead of a
variable (skillLevel).







1

Sams Teach Yourself Java 2 Rogers Cadenhead