String类型:
String类型并不是基本类型,但是它常被误以为是一种基本类型。
String类型是Immutable的,一旦创建就不能够被改变。
不可改变的具体含义是指:
不能增加长度
不能减少长度
不能插入字符
不能删除字符
不能修改字符
一旦创建好这个字符串,里面的内容 永远 不能改变
String字符串的拼接:(+/+=)
字符串拼接实质是创建了新的字符串对象 ,原字符串对象没有发生改变
String字符串的替换:(replaceAll 替换所有 ,replaceFirst 只替换第一个)
这里的替换并非修改了原字符串,而是生成了新的字符串。
我的理解是,对String字符串对象的所有操作都不是更改对象本身,而是返回了新的字符串;就像replaceAll之前和之后不是一个对象了!
跑了网上网友给出的一个例子,运行之后秒懂:
String a = "ABC";
String anotherA = a.replaceAll("A", "B");
System.out.println(a);
System.out.println(anotherA);
System.out.println(a==anotherA);
StringBuffer b = new StringBuffer("ABC");
StringBuffer anotherB = b.replace(0, 1, "B");
System.out.println(b);
System.out.println(anotherB);
System.out.println(b==anotherB);
执行结果:
I/System.out: ABC
I/System.out: BBC
I/System.out: false
I/System.out: BBC
I/System.out: BBC
I/System.out: true
参考:
https://zhidao.baidu.com/question/272799186.html
http://how2j.cn/k/number-string/number-string-manipulate/325.html#step718