String类型的值不能修改

11 篇文章 0 订阅

String 不可变的理解

  1. String 类是被 final 修饰的,不能被继承;
  2. 在用 “+” 号连接字符串的时候会创建新的字符串;
  3. String s = new String(“Hello world”); 可能创建两个对象,也可能创建一个对象。如果静态区中有 “Hello world” 字符串常量对象的话,则仅仅在堆中创建一个对象;若无此对象,则堆上和静态区中都需要创建对象。
  4. 在Java中,通过使用 “+” 符号来窗帘字符串的时候,实际上底层会转成通过 StringBuilder 实例的 append() 方法来实现。

通过一个例子来说明:

public class Example {
    String str = new String("good");
    char[] ch = {'a', 'b', 'c'};

    public static void main(String args[]) {
        Example ex = new Example();
        ex.change(ex.str, ex.ch);
        System.out.print(ex.str + " and ");
        System.out.print(ex.ch);
    }

    public void change(String str, char ch[]) {
        str = "test ok";
        ch[0] = 'g';
    }
}

A good and abc
B good and gbc
C test ok and abc
D test ok and gbc

正确答案:B
理解:因为str的类型是String,String的值是不能修改的,所谓的修改只会新创建新的String,而ex.str依然指向原来的String地址,所以它的值没有改变,依旧是“good”。

补充:

public class Test {
    public static void main(String[] args) {
        String str = "Hello";
        str += "World";
        System.out.println(str);
    }
}

输出:
在这里插入图片描述
上面的代码虽然修改了String对象的内容,但是还是能够正常运行。
理解:String类对象内容不能修改,但并不代表其引用不能改变。
String对象内容的改变实际上是通过内存地址“断开-连接”变化来完成的,str只是由原来指向"hello"变为指向“hello world”而已,而其原来的指向内容,是没有改变的。

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值