int currentTemperature = 28; int targetTemperature = 26;
if (currentTemperature > targetTemperature) {
System.out.println("当前温度偏高,开启制冷模式");
} else if (currentTemperature < targetTemperature) {
System.out.println("当前温度偏低,开启制热模式");
} else {
System.out.println("温度适宜,保持当前状态");
}
String str1 = "hello"; String str2 = new String("hello"); String str3 = "hello";
System.out.println(str1 == str2); // false System.out.println(str1 == str3); // true System.out.println(str1.equals(str2)); // true
public boolean validateLogin(String inputUsername, String inputPassword) {
// 从数据库获取的正确用户名和密码
String correctUsername = "admin";
String correctPassword = "123456";
// 比较用户名(通常不区分大小写)
boolean usernameMatch = inputUsername.equalsIgnoreCase(correctUsername);
// 比较密码(通常区分大小写)
boolean passwordMatch = inputPassword.equals(correctPassword);
return usernameMatch && passwordMatch;
}
// 单一条件判断 - 繁琐的写法 if (userAge >= 18) {
if (hasIdCard) {
if (isLocalResident) {
System.out.println("可以办理银行卡");
}
}
}
// 使用逻辑运算符 - 简洁明了 if (userAge >= 18 && hasIdCard && isLocalResident) {
System.out.println("可以办理银行卡");
}
// 低效写法 - 每次循环都计算list.size() for (int i = 0; i < list.size(); i++) {
if (list.get(i) > threshold) {
// 处理逻辑
}
}
// 优化写法 - 预先计算size int size = list.size(); for (int i = 0; i < size; i++) {
if (list.get(i) > threshold) {
// 处理逻辑
}
}