java如何判断
判断的基本语法
在Java中,判断主要通过条件语句实现,最常用的是if、else if和else结构。基本语法如下:
if (条件表达式) {
// 条件为真时执行的代码
} else if (另一条件表达式) {
// 前一条件为假且当前条件为真时执行
} else {
// 所有条件均为假时执行
}
条件表达式
条件表达式通常返回布尔值(true或false),常见形式包括:
- 比较运算:
==、!=、>、<、>=、<= - 逻辑运算:
&&(与)、||(或)、!(非) - 对象判断:
instanceof检查类型int a = 10; if (a > 5 && a < 15) { System.out.println("a在5到15之间"); }
多分支判断
当需要处理多个离散值时,switch语句比多重if更简洁:
int day = 3;
switch (day) {
case 1:
System.out.println("周一");
break;
case 2:
System.out.println("周二");
break;
default:
System.out.println("其他日期");
}
三元运算符
简单条件判断可使用三元运算符(?:)简化代码:
int score = 75;
String result = (score >= 60) ? "及格" : "不及格";
空值判断
处理对象时需注意空指针检查:
String str = null;
if (str != null && !str.isEmpty()) {
System.out.println("字符串非空");
}
集合判断
对集合类(如List、Map)的判断:
List<String> list = new ArrayList<>();
if (list != null && !list.isEmpty()) {
System.out.println("列表有元素");
}
自定义条件
可通过实现Predicate接口或方法引用实现灵活判断:

Predicate<Integer> isEven = num -> num % 2 == 0;
if (isEven.test(4)) {
System.out.println("偶数");
}






