Ternary operator (They have three operands)
condition ? value1 : value2
The value of the above expression is
either value1 if the condition is true
or value2 if it is false.
Example 1:
if (count == 0)
Avg = 0;
else
Avg = sum / count;
same as
Avg = (count == 0) ? 0 :
sum / count;
Boolean
expression value if Boolean is false
if
value if Boolean is true
Example 2:
import java.util.Scanner;
public class Tester
{
public static void main(String [] args)
{
int x, y ;
Scanner input = new Scanner(System.in);
System.out.println("Enter your score");
x = input.nextInt();
y = x >= 0? x : -x;
System.out.println("Absolute value of "+ x + " is " + y + ".");
}
}