相关疑难解决方法(0)

在Java中连接字符串是否总会导致在内存中创建新字符串?

我有一个不符合屏幕宽度的长字符串.例如.

String longString = "This string is very long. It does not fit the width of the screen. So you have to scroll horizontally to read the whole string. This is very inconvenient indeed.";
Run Code Online (Sandbox Code Playgroud)

为了便于阅读,我想到了这样写 -

String longString = "This string is very long." + 
                    "It does not fit the width of the screen." +
                    "So you have to scroll horizontally" +
                    "to read the whole string." +
                    "This is very inconvenient indeed.";
Run Code Online (Sandbox Code Playgroud)

但是,我意识到第二种方式使用字符串连接,并将在内存中创建5个新字符串,这可能会导致性能下降.是这样的吗?或者编译器是否足够智能,以确定我需要的只是一个字符串?我怎么能避免这样做?

java compiler-construction string string-concatenation

24
推荐指数
2
解决办法
5320
查看次数

字符串池可以包含两个具有相同值的字符串吗?

字符串池可以包含两个具有相同值的字符串吗?

String str = "abc";
String str1 = new String("abc");

   Will the second statement with `new()` operator creates two objects of `string` "abc", one on `heap` and another on `string` pool? 

   Now if i call intern() on str1 ie str1.intern(); as a third statement, will str1 refer to the "abc" from String pool? 

  If yes then what will happen to the object that was created on heap earlier by the new(). Will that object be eligible for garbage collection.?
  If …
Run Code Online (Sandbox Code Playgroud)

java string

1
推荐指数
1
解决办法
1763
查看次数