Monthly Archives: June 2013

Family of String Brothers!

Strings are very frequently used in Java programs. Strings in Java are immutable. If you look at the source code of String you find that java.lang.String has the following properties.

 /** The value is used for character storage. */
 private final char value[];
/** The offset is the first index of the storage that is used. */
 private final int offset;
/** The count is the number of characters in the String. */
 private final int count;

The array is used to store the values of this String.

As Strings are immutable they can be freely shared. This property is utilized in the method substring(). The method substring will use a reference to the same String and only change the offset and the lenght value for the String. The same string is in this case used several times.

Therefore using substring requires only a constant amount of time (and almost no additional memory) and can be freely used.

The operation concat() (which is called by the + operator) combines two Strings. This method has to copy the characters of the two Strings and therefore takes time and extra space which is propotional to the length of the two strings .

Now String Builder,

The object StringBuilder has a more effectly way of concatenate Strings. It works similar to the class ArrayList by allocating a predefined array for storing the characters and keeps track of the used space. Every time the space is exceeded then it will extend the available capacity).

Key Differences!

  • String is immutable in JAVA , whereas String Buffer is mutable.
  • StringBuffer.append() method is used to perform String concatenation in Java.
  • When using (+) operator to concatenate String in Java , so according to java implementation at bytecode level (+) concatenation operator is replaced with StringBuilder or StringBuffer based upon JVM implements Java.
  • Conversion between and String and StringBuffer is quite easy.
  • MAJOR difference between String and StringBuffer is that they donot share same Type hierarchy, i.e you can not cast String to StringBuffer else it will generate ClassCastException.

Must Read References!

1-http://www.vogella.com/articles/JavaConcurrency/article.html#immutability

2-http://stackoverflow.com/questions/1036719/how-many-people-have-been-stung-by-java-substring-memory-issues

Advertisements