Java基础:条件运算符、instanceof运算符

Java条件运算符、instanceof运算符



条件运算符

  • 语法格式:

条件?表达式1:表达式2

  • 运算规则:

条件运算符也称三元运算符。对于i?x:y,当i值为true时,取x的值;i值为false时,取y值。

例如:

int i = a==10 ? 15 : 20;	
//当条件a==10为true时,就把15赋值给i;当条件a==10为false时,就把20赋值给i
//上式等价于:
	int i;
    if (a==10){
        i = 15;
    }else {
        i=20;
    }
public class Demo {
    public static void main(String[] args) {

        int max = max(10,20);
        System.out.println(max);

    }

    //比大小
    public static int max(int a,int b) {

        if (a == b) {
            System.out.println("这两个数相等");
            return 0;//终止方法
        }
        return a > b? a : b;//条件运算符判断

    }
}
  • 结合性: ?: 的结合顺序是由右向左

    例如表达式 a? b: c? d: e? f: g 解释为 (a? b: (c? d: (e? f: g)))


instanceof运算符

该运算符用于操作对象实例,检查该对象是否是一个特定类型(类类型或接口类型)

  • 语法

对象 instanceof 类类型/接口类型

如果运算符左侧变量所指的对象,是操作符右侧类或接口的一个对象,那么结果为真。

String name = "Dt";
boolean result = name instanceof String; 
System.out.println(result);	//name 属于 String类 ,所以编译出的结果为true

更多例子:

class Person {
}

class Teacher extends Person {
}

public class Student extends Person {

    public static void main(String[] args) {

        //Object>String
        //Object>Person>Teacher
        //Object>Person>Student
        Object object = new Student();

        System.out.println(object instanceof Student);//true
        System.out.println(object instanceof Person);//true
        System.out.println(object instanceof Object);//true
        System.out.println(object instanceof Teacher);//false
        System.out.println(object instanceof String);//false

        System.out.println("=======================");

        Person person = new Student();
        System.out.println(person instanceof Student);//true
        System.out.println(person instanceof Person);//true
        System.out.println(person instanceof Object);//true
        System.out.println(person instanceof Teacher);//false
        //System.out.println(person instanceof String);//编译报错

        System.out.println("=======================");

        Student student = new Student();
        System.out.println(student instanceof Student);//true
        System.out.println(student instanceof Person);//true
        System.out.println(student instanceof Object);//true
//        System.out.println(student instanceof Teacher);//编译报错
//        System.out.println(student instanceof String);//编译报错

    }

}

编译结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值