what is the advantage of string object as compared to string literal

后端 未结 6 1984
你的背包
你的背包 2021-01-02 16:59

i want to know where to use string object(in which scenario in my java code). ok i understood the diff btwn string literal and string object, but i want to know that since

6条回答
  •  春和景丽
    2021-01-02 17:36

    String literals are converted to String objects, and as others pointed out, creating explicit String objects is unnecessary and inperformant, as it defeats String pooling.

    However, there is one situation where you want to create new Strings explicitly: If you use just a small part of a very long String. String.substring() prevents the original String from getting GC'd, so you can save memory when you write

    String s = new String(veryLongString.substring(1,3));
    

    instead of

    String s = veryLongString.substring(1,3);
    

提交回复
热议问题