前言
条件运算符在实际开发的过程中常用,必须熟练掌握!
正文
条件运算符,是一种三元运算符(三目运算符)。顾名思义,"三元"指的是一个表达式含有三个操作对象;在Java中,条件运算符主要作用就是用来简化 if...else 语句。
通过 ? 和 : 运算符判断 ? 前的语句是true还是false,并根据结果返回 : 前后的值。
格式如下:
variable = (expression) ? expressionIsTrue : expressionIsFalse;
-
expression :是被判断的表达式,为True或False;
-
expressionIsTrue : expression所返回的值为True,并赋给variable;
-
expressionIsFalse : expression所返回的值为False,并赋给variable;
特别需要注意:expressionIsTrue和expressionIsFalse需要返回相同或者兼容的数据类型,并且类型不能是void!
实例
/**
* @author Echohol
*条件运算符
*/
public class DemoternaryOperators {
static String str = "HelloWorld";
static String inputwords = "";
public static void main(String[] args) {
inputwords = str.length() > 0 ? "Not null" : "Null";
System.out.println(inputwords);
/*
void surprise(){
System.out.println("I'm the champion!");
}
void pity(){
System.out.println("NULL!!!!!!!!!!!");
}
static DemoternaryOperators result = new DemoternaryOperators();
*/
/*
(str == null) ? result.pity() : result.surprise();
上面的语句执行不了,只能用下面的if语句代替
因为后两个表达式的返回值不能为void
*/
/*
if (str != null) {
System.out.println("I'm the champion!");
}
else{
System.out.println("NULL!!!!!!!!!!!");
}
*/
}
}
结果 :
Not null
参考
Java Ternary Operator: A Step-By-Step Guide
《Java实用教程》——郑阿奇等
特别声明:转载请注明出处!