Sunday, 7 December 2008

The Dichotomy of Mutable and Immutable in Java

String and StringBuffer are immutable and mutable analogues of one another. StringBuffers are used to implement the binary string concatenation operator.

Example: x = "a" + "b" + "c";
is compiled to x = new StringBuffer().append("a").append("b").append("c").toString();

You can also call append on ints, chars, floats and doubles.

When you instantiate a StringBuffer it has an initial capacity of 16 characters, however e.g. new StringBuffer(500) will create a StringBuffer with an initial capacity of 500 characters.

An interesting article on a mutable and immutable design pattern (as exemplified by String and StringBuffer) can be found on javaworld.

No comments:

Blog Archive