Java的String使用

来源:互联网 发布:矩阵加1 编辑:程序博客网 时间:2024/05/17 04:18

Here are a set of diagrams to explain Java String’s immutability.

1. Declare a string

String s="abcd";

String-Immutability-1

2. Assign a string variable to another string variable

String s2=s;

String-Immutability-2

3. Concat string

s=s.concat("ef");


string-immutability

Summary

Once a string is created in memory(heap), it can not be changed. We should note that all methods of String do not change the string itself, but rather return a new String.

If we need a string that can be modified, we will need StringBuffer or StringBuilder. Otherwise, there would be a lot of time wasted for Garbage Collection, since each time a new String is created. Here is an example of StringBuilder usage.

原创粉丝点击