StringBuilder and StringBuffer

In java, the value of a String is fixed after the String is created; Strings are immutable, or unchangeable. When you write someString=”Hello”; and follow it with someString=”Goodbye”; you have nerither changed the contents of computer memory at the address represented by someString nor eliminated the characters “Hello”. Instead, you have stored “Goodbye” at a new computer memory location and stored the new address in the someString variable. If you wan to modify someString from “Goodbye” to “Goodbye Everybody”, you cannot add a space and “Everybody” to the someString that contains “Goodbye” Instead, you must create an entirely new String,”Goodbye Everybody”, and assign it to the someString address.

To circumvent these limitations, you can use either the StringBuilder or StringBuffer class. You use one of these classes, which are alternatives to the String class, when you know a String will be modified; Usually, you can use a StringBuffer or StrinBuilder object anywhere you would use a String. Like the String class, these two classes are part of the java.lang package and are automatically imported into every program. The classes are identical except for the following:

StringBuilder is more efficient.

StringBuffer is thread safe. This means you should use it in applications that run multiple threads, which are paths of control taken during program execution.

You can create a StringBuilder object that contains a String with a statement such as the following:

StringBuilder message = new StringBuilder(“Hello there”);

A StringBuilder object, contains a memory block called a buffer, which might or might not contain a string. Even if it does contain a string, the string might not occupy the entire buffer. In other words, the length of a string can be different from the length of the buffer. The actual length of the buffer is the capacity of the StringBuilder object.

You can change the length of a string in a StringBuilder object with the setLength() method. When you increase a StringBuilder object’s length to be longer than the String it holds, the extra characters contain “\u0000”. If you use the setLength() method to specify a length shorter than its String, the string is truncated.

Using StringBuilder objects provides improved computer performance over String objects because you can insert or append new contents into a StringBuilder. In other words, unlike immutable Strings, the ability of StringBuilders to be modified makes them more efficient when you know string contents will change.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值