Building Strings in Java

Building and manipulating strings is one of the most common tasks performed in any programming language. In Java, the String class provides the functionality of creating and manipulating the strings. Strings are, as you know, just a sequence of characters. Let us see how String and StingBuffer classes can be used to handle strings in more efficient ways.

Let’s first understand how String class works:

String str="Lalit";

This statement is equivalent to the object creation of String class in the following way:

char characters[]={'L', 'a', 'l', 'i', 't'};
String str=new String(characters);

The append operation on strings is often required while building a string. Generally, programmers use concatenation operator ( + ) to join two strings, for example:

String str = "Java is ";
str=str + "cool";       // (or str+="cool");

But the instances of String class are immutable (i.e. unchangeable, read-only) -they cannot be changed once created. So, to implement the string concatenation operator, Java uses the StringBuffer class (which is mutable).

String str = "Java is " + "cool ";

Internally the above statement is implemented as:

String str = new StringBuffer().append("Java is ").append("cool").toString();

It is clear that while building large strings it is better to use StringBuffer class and its methods (like append) instead of using String class and + operator. StringBuffer code will execute faster and will take lesser memory.

I hope this tiny tip was useful for you and will save time for you and memory for your Java programs!

Leave a Comment

Your email address will not be published. Required fields are marked *