三元运算符也称为条件运算符。该运算符由三个操作数组成,用于评估布尔表达式。运算符的目标是确定应将哪个值分配给变量。运算符写为-
variable x = (expression) ? value if true: value if false
以下是一个例子-
public class Test { public static void main(String args[]) { int a, b; a = 10; b = (a == 1) ? 20: 30; System.out.println( "Value of b is : " + b ); b = (a == 10) ? 20: 30; System.out.println( "Value of b is : " + b ); } }
输出结果
这将产生以下结果-
Value of b is : 30 Value of b is : 20