zixue

本文探讨了Java中final关键字对字符串常量池的影响,以及equals()方法与==操作符的区别。通过实例展示了str1和str2虽然值相同,但由于str1被final修饰导致str3和str4在内存中的不同存储位置,解释了str3==str4为false的原因。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package tk;

public class application
{
    public static void main(String[] args){
       final String str1 = "hello" ;
       String str2 = "hello";
       System.out.println(str2 == "hello");
        System.out.println(str1 == str2);
       String str3 =str1 + "world";
        String str4 =str2 + "world";
        System.out.println(str3);
        System.out.println(str3 == str4);
        System.out.println(str3.equals(str4));

    }
}

equals()比较的是自变量的数值,而==比较的则是自变量引用的是否是同一对象

true
true
helloworld
false
true

str3==str4false的原因是:str1被final修饰后变为常量,所以str3为常量加常量在常量池里面,str4则是变量加常量;结果在堆里面,所以结果不同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值