三元运算符是if-else语句的简写形式。它有三个操作数,因此名称是三元的。一般格式是 condition ? if true : if false
上述声明意味着如果条件评估为真,那么在'?'之后执行语句。否则在':'之后执行语句。 // Java program to illustrate
// max of three numbers using
// ternary operator.
public class operators
{
public static void main(String[] args)
{
int a = 20, b = 10, c = 30, result;
//result holds max of three
//numbers
result = ((a > b) ? (a > c) ? a :
c : (b > c) ? b : c);
System.out.println("Max of three numbers = "+result);
}
}
输出: Max of three numbers = 30