首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Java语言中,String和StringBuffer有什么不同?

在Java语言中,String和StringBuffer有什么不同?
EN

Stack Overflow用户
提问于 2010-03-14 01:25:47
回答 7查看 181.9K关注 0票数 62

在Java语言中,String和StringBuffer有什么不同?

字符串有最大长度限制吗?

EN

回答 7

Stack Overflow用户

发布于 2013-03-22 14:54:16

代码语言:javascript
复制
String                                          StringBuffer

Immutable                                       Mutable
String s=new String("karthik");                StringBuffer sb=new StringBuffer("karthik")
s.concat("reddy");                             sb.append("reddy");
System.out.println(s);                         System.out.println(sb);
O/P:karthik                                    O/P:karthikreddy

--->once we created a String object            ---->once we created a StringBuffer object
we can't perform any changes in the existing  we can perform any changes in the existing
object.If we are trying to perform any        object.It is nothing but mutablity of 
changes with those changes a new object       of a StrongBuffer object
will be created.It is nothing but Immutability
of a String object

Use String--->If you require immutabilty
Use StringBuffer---->If you require mutable + threadsafety
Use StringBuilder--->If you require mutable + with out threadsafety

String s=new String("karthik");
--->here 2 objects will be created one is heap and the other is in stringconstantpool(scp) and s is always pointing to heap object

String s="karthik"; 
--->In this case only one object will be created in scp and s is always pointing to that object only
票数 24
EN

Stack Overflow用户

发布于 2011-03-05 00:58:25

String是一个不可变的类。这意味着一旦你像这样实例化了一个字符串的实例:

代码语言:javascript
复制
String str1 = "hello";

内存中的对象不能更改。相反,您必须创建一个新的实例,复制旧的字符串并附加任何其他内容,如本例所示:

代码语言:javascript
复制
String str1 = "hello";
str1 = str1 + " world!";

实际发生的情况是,我们没有更新现有的str1对象...我们一起重新分配新的内存,复制"hello“数据并附加”world!“最后,将str1引用设置为指向这个新内存。因此,它看起来更像是这样的:

代码语言:javascript
复制
String str1 = "hello";
String str2 = str1 + " world!";
str1 = str2;

因此,这个“复制+粘贴并在内存中到处移动东西”的过程如果重复地完成,特别是递归地完成,可能会非常昂贵。

当您处于不得不一遍又一遍地做事情的情况下,请使用StringBuilder。它是可变的,可以将字符串附加到当前字符串的末尾,因为它是由growing array返回的。

票数 10
EN

Stack Overflow用户

发布于 2010-03-14 01:27:03

StringBuffer用于从多个字符串创建单个字符串,例如,当您想要在循环中附加字符串的部分时。

当只有一个线程访问StringBuffer时,您应该使用StringBuilder而不是StringBuffer,因为StringBuilder不是同步的,因此速度更快。

AFAIK在作为一种语言的Java中,字符串大小没有上限,但JVM可能有上限。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2439243

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档