Building Strings in Java

Learn how to create strings in Java; how strings are different from character arrays and how to build large strings for efficient execution of programs.

Building and manipulating strings is one of the most common task performed in any programming language. In Java, the String class provides the functionality of creating and manipulating the strings (which are just sequence of characters):

String str="Lalit";

is equivalent to

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, like:

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

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

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

is internally implemented as:

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

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.

Leave a Reply

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