条件运算符

前言

       条件运算符在实际开发的过程中常用,必须熟练掌握!

正文

        条件运算符,是一种三元运算符(三目运算符)。顾名思义,"三元"指的是一个表达式含有三个操作对象;在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实用教程》——郑阿奇等

        特别声明:转载请注明出处!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值