String can't change. But int, char can change

后端 未结 7 1517
暖寄归人
暖寄归人 2020-12-03 21:24

I\'ve read that in Java an object of type String can\'t change. But int and char variables can. Why is it? Can you give me an example?

Thank you. (I am a newer -_- )

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 22:05

    Strings are immutable in java. Nevertheless, you can still append or prepend values to strings. By values, I mean primitive data types or other strings.

    However, a StringBuffer is mutable, i.e. it can be changed in memory (a new memory block doesn't have to be allocated), which makes it quite efficient. Also, consider the following example:

    StringBuffer mystringbuffer = new StringBuffer(5000);
    
    for (int i = 0; i<=1000; i++)
    {
        mystringbuffer.append ( 'Number ' + i + '\n');
    }
    
    System.out.print (mystringbuffer);
    

    Rather than creating one thousand strings, we create a single object (mystringbuffer), which can expand in length. We can also set a recommended starting size (in this case, 5000 bytes), which means that the buffer doesn't have to be continually requesting memory when a new string is appended to it.

    While a StringBuffer won't improve efficiency in every situation, if your application uses strings that grow in length, it would be efficient. Code can also be clearer with StringBuffers, because the append method saves you from having to use long assignment statements.

提交回复
热议问题