Bootstrap

java中的条件运算符三目运算

语法格式:

x?y:z

  其中x为Boolean类型表达式,先计算x的值,若为true,则整个运算的结果为表达式y的值,否则整个运算结果为表达式z的值。

 

示例代码:

public class sanmu {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int score=80;
		int x=-100;
		String type=score<60?"不及格":"及格";
		int flag =x>0?1:(x==0?0:-1);
		System.out.println("type="+type);
		System.out.println("flag="+flag);
	}

}

结果:

type=及格
flag=-1

 

;