java学习总结6:关系运算符

关系运算符

运算符描述示例注意事项
==等于a == b引用类型比较对象的引用,基本类型比较值
!=不等于a != b同上
>大于a > b用于比较数字的大小
<小于a < b用于比较数字的大小
>=大于等于a >= b用于比较数字的大小,包含相等情况
<=小于等于a <= b用于比较数字的大小,包含相等情况
instanceofinstanceof 运算符用于检查对象是否是特定类的实例a instanceof b用于类之间的继承关系判断,或者接口的实现判断。

注:在Java中,== 运算符用于比较两个变量是否指向同一个对象。然而,在不同的情况下,== 的行为可能会出乎预期,因此在使用时需要注意以下几点:

  1. 基本数据类型比较:对于基本数据类型(如 int、float 等),== 比较的是它们的值是否相等。
  2. 引用类型比较:对于引用类型(如类、接口、数组等),== 比较的是对象的引用地址是否相等,即它们是否指向同一个对象。
  3. 字符串比较:对于字符串,使用 == 比较的是字符串的引用地址,而不是内容。为了比较字符串的内容,应使用 .equals() 方法。
  4. 自动装箱拆箱:使用 == 比较包装类对象时,会涉及自动装箱和拆箱。在一些情况下,自动装箱可能导致不同的对象被创建,因此 == 可能会返回 false。
  5. 常量池:Java中的字符串常量可能存储在常量池中,同样的字符串字面量在编译期间会被优化为同一个对象。因此,使用 == 比较字符串字面量是安全的。

代码示例:

public class Main {
    public static void main(String[] args) {
        int num1 = 5;
        int num2 = 5;
        System.out.println(num1 == num2);  // true

        Integer numObj1 = 10;
        Integer numObj2 = 10;
        System.out.println(numObj1 == numObj2);  // true

        String str1 = "Hello";
        String str2 = "Hello";
        String str3 = new String("Hello");
        System.out.println(str1 == str2);  // true (both refer to the same constant in the string pool)
        System.out.println(str1 == str3);  // false (str3 refers to a new object)

        String str4 = "World";
        String str5 = new String("World").intern();
        System.out.println(str4 == str5);  // true (str5 refers to the interned string in the string pool)

        Integer numObj3 = 1000;
        Integer numObj4 = 1000;
        System.out.println(numObj3 == numObj4);  // false (different objects, due to autoboxing)

        Integer numObj5 = 50;
        int num6 = 50;
        System.out.println(numObj5 == num6);  // true (auto-unboxing converts numObj5 to int)

        Integer numObj7 = 128;
        Integer numObj8 = 128;
        System.out.println(numObj7 == numObj8);  // false (outside the cached range [-128, 127])
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值