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

1|0Java条件运算符、instanceof运算符

1|1条件运算符

  • 语法格式:

条件?表达式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)))


1|2instanceof运算符

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

  • 语法

对象 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

__EOF__

本文作者userName
本文链接https://www.cnblogs.com/dt746294093/p/14589203.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   D..T  阅读(310)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
点击右上角即可分享
微信分享提示