Java中String引用类型讨论
问题提出
在Java语言中,String类型在作为函数传参时,String类型是表现出“非对象”特性的。举例如下:
public class Test {
public static void main(String args[]) {
System.out.println("hello,world!");
Test testCls = new Test();
testCls.test0();
}
public void test0(){
String name = "louis";
addLastName(name);
System.out.println(name);
}
public void addLastName(String name){
name += "lan";
System.out.println(name);
}
}
最终的结果如下:
hello,world!
louislan
louis
问题解释
这是因为在Java中,我们将String类型认定为常量(具体可看Java api文档)。当他们被创建后是不可以改变的,所以当String类型进行改变操作时,会另外实例化一个String(相当于new String)。
问题解决
Java中提供了另一个类型,叫作StringBuffer类型,他能达到我们想要的结果。如下例:
public class Test {
public static void main(String args[]) {
System.out.println("hello,world!");
Test testCls = new Test();
testCls.test0();
}
public void test0(){
StringBuffer name = new StringBuffer("louis");
addLastName(name);
System.out.println(name);
}
public void addLastName(StringBuffer name){
name.append(" lan") ;
System.out.println(name);
}
}
最终输出结果为:
hello,world!
louis lan
louis lan

本文探讨了Java中String类型的不可变性及其在函数传参时的表现,通过实例对比了String与StringBuffer的行为差异,揭示了StringBuffer如何实现字符串的动态修改。
1830

被折叠的 条评论
为什么被折叠?



