String和常量池值的变化

 

public static void main(String[] args) {
        Integer i1 = new Integer(1);
        Integer i2 = new Integer(1);
        // i1,i2分别位于堆中不同的内存空间
        System.out.println("i1 == i2:" + (i1 == i2));// 输出false

        String s1 = "china";

        String s2 = "china";

        String ss1 = new String("china");

        String ss2 = new String("china");

        System.out.println("s1 == s2:" + (s1 == s2));
        System.out.println("ss1 == ss2" + (ss1 == ss2));
        System.out.println("s1 == ss2" + (s1 == ss2));

        // 利用Java反射机制改变string的值
        Field f = null;
        Field f1 = null;
        try {
            f = s1.getClass().getDeclaredField("value");
            f1 = ss1.getClass().getDeclaredField("value");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        f.setAccessible(true);
        f1.setAccessible(true);
        try {
            f.set(s1, new char[] { 'c', 'h', 'i', 'n', 'b' });
            f1.set(ss1, new char[] { 'c', 'h', 'i', 'n', 'b' });
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("改变后的s1的值:" + s1);
        System.out.println("s2的值是:" + s2);
        System.out.println("ss1的值是:" + ss1);
        System.out.println("s1 == s2:" + (s1 == s2));
        System.out.println("ss1 == ss2" + (ss1 == ss2));
        System.out.println("s1 == ss2" + (s1 == ss2));
        System.out.println("============分割线==================");
        System.out.println("改变后的ss1的值:" + ss1);
        System.out.println("ss2的值是:" + ss2);

    }

 

 

打印的结果:

i1 == i2:false
s1 == s2:true
ss1 == ss2false
s1 == ss2false
改变后的s1的值:chinb
s2的值是:chinb
ss1的值是:chinb
s1 == s2:true
ss1 == ss2false
s1 == ss2false
============分割线==================
改变后的ss1的值:chinb
ss2的值是:china

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java高知社区

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值