下面的示例说明了 Java 比较运算符的用法:==、!=、>、<、>=、<=。
public class MyClass {
public static void main(String[] args) {
System.out.println("10 == 10: "+ (10 == 10));
System.out.println("10 != 10: "+ (10 != 10));
System.out.println("10 < 20: "+ (10 < 20));
System.out.println("10 > 20: "+ (10 > 20));
System.out.println("10 <= 20: "+ (10 <= 20));
System.out.println("10 >= 20: "+ (10 >= 20));
}
}
上述代码的输出将是:
10 == 10: true
10 != 10: false
10 < 20: true
10 > 20: false
10 = 20: false
这些比较运算符通常返回布尔结果,这非常有用,可以用来构造条件语句,如下例所示:
public class MyClass {
static void range_func(int x){
//&&运算符用于组合条件
//仅当 x >= 10 且 x <= 25 时才返回 true
if(x >= 10 && x <= 25)
System.out.println(x +" belongs to range [10, 25].");
else
System.out.println(x +" do not belongs to range [10, 25].");
}
public static void main(String[] args) {
range_func(15);
range_func(25);
range_func(50);
}
}
上述代码的输出将是:
15 belongs to range [10, 25].
25 belongs to range [10, 25].
50 do not belongs to range [10, 25].