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
posted @ 2021-03-28 17:17  D..T  阅读(291)  评论(0编辑  收藏  举报