Skip to main content

String manipulation in Java

One topic most of the developers in early days of their career overlook while programming is STRING MANIPULATION. This article will throw some light on this topic, so that one can make habit of some efficient coding. I am going to give some insight into Java string manipulation and some better ways to do string manipulation.
In Java String objects are immutable, what it means is once you create a String object in Java, it can not be changed/modified. For example look at the following code.
   String a = "A String Object";
   a = "Second String Object";
  
In the above code, we created a String object 'a' at line#1 with the value "A String Object", and in line#2 we tried to change the value of the object 'a' to "Second String Object". As I mentioned little earlier, when you create a String object in Java, it can not be changed. In line#2 when you try to change the value of object 'a', JVM [Java Virtual Machine] will create a new String object with the new value and assign its reference to object 'a', and the old reference will be marked for garbage collection. Let's look at another piece of code.
   String a = "A String Object, ";
   a = a + "created in Java";
  
It looks almost similar to the first piece of code. Difference is after creating a String object at line#1, at line#2 - we tried to append another string "created in Java" to the existing one. Obviously result we expected is "A String Object, created in Java". Internally what JVM does is it creates a new Java object with the new appended string and assigns its reference to object 'a', old references will be marked for garbage collection.
This cost of this string manipulation [above pieces of code] might look negligible to any one, but think about an application with pieces of code like the one above spread all over its source. Think how many String objects gets created and marked for garbage collection at one run. This all results to many CPU cycles allocated for creation of String objects and garbage collecting unreferenced String Objects.
Now let's look at one way of doing String manipulation in a better way. Java provides two classes which allow you to modify String values.
These two objects are almost same with only one difference. StringBuilder class is unsynchronized, where are StringBuffer is synchronized. In short StringBuffer is thread safe, where as StringBuilder is not. We can use these classes to do String manipulation efficiently in our code. When to use StringBuilder and when to use StringBuffer? Answer to this question is when your code is accessed by single thread at any time then it is better to use StringBuilder, which gives better performance in this scenario. And when your code is accessed by multiple threads then you need to use StringBuffer because its thread safe.
Now lets look at an example using one of these classes. Think of a situation where you have String objects representing parts of address of one user/company or something like that. Think that you've four String objects 'streetAddress', 'city', 'state', and 'country' with values initialized properly, and you want to generate one String with all these values. For example if the above mentioned objects are initialized as given below,
   streetAddress = "Plot#10, Road#7";
   city = "Hyderabad";
   state = "Andhrapradesh";
   country = "India";
  
And you want to have a composite string like "Plot#10, Road#7, Hyderabad, Andhrapradesh, India". One inefficient way of doing is using the overloaded '+' operator like
   streetAddress + "," + city + "," + state + "," + country
  
Now the better way using StringBuilder class is
   StringBuilder sb = new StringBuilder();
   sb.append(streetAddress).appent(',').append(city).append(',')
     .append(state).append(',').append(country);
  
Most common place where developers can improve string manipulation related code is JSP pages. If you take the above example, to print the address, some developers code it like
   <%=streetAddress + "," + city + "," + state + "," + country %>
  
In a JSP page one object [instance of JSPWriter, 'out' object available on a JSP] will already be created to generate the output. If you write code which is similar to the one above, JVM creates unnecessary String objects for each of the '+' operator you use. After reading this article till this point you can think of using StringBuilder/StringBuffer, but that might not be the correct way to do it. Why?, as I mentioned above there will be one object 'out' created already, creating another StringBuilder/StringBuffer object doesn't make sense. Then obvious solution is to use the 'out'. You can write something like the one below to generate the address string.
   <%=streedAddress%>, <%=city%>, <%=state%>, <%=country%>
  
If you think the above code makes the JSP look little complex, then you can write a static method to do the job for you. This method can take the 'out' object [JSPWriter instance] and the values to be appended. In that method you can call the 'append()' method on JSPWriter object 'out' to append the values.
That is all I have for now, about String manipulation. Hope it helps some guys to do some efficient coding.
HAPPY CODING!
Technorati Profile

Comments

Mohammed said…
In Java, Interfaces make things simple.

Notice that StringBuilder, StringBuffer as well as JSPWriter implements Appendable interface.

for the mentioned example of generating complete address on a JSP, write a static method which take Appendable as an argument and perform append operations on it without worrying about the implementation class.
Sharath Kedika said…
why do we need a object do simple string manipulation ????
Rakesh A said…
In Java all string are Objects, instances of String class :-)

Popular posts from this blog

Simple Accordion using Java Script and CSS

Well you can find many online, but it's difficult to find one with out any dependent API. Most of the available accordions use other APIs for animation and other stuff. For those who just want accordion with out any other stuff, this one is the perfect one. It's very simple and you don't have to be a geek to understand it. Basic knowledge of Java script and CSS will do to understand how this works. In this article I'll take you through the steps of developing an accordion. Couple of minutes you are ready to write your own. Well then let's start developing one. Layout of the HTML block looks something like the one below Lets look at the CSS first which is very simple. /** container styles **/ .ra-p, .ra-cp { padding: 0 0 0.1em; } /**** heading styles ****/ .ra-p h2, .ra-cp h2 { margin: 0px; padding: 0.2em; cursor: pointer; color: #fff; background-color: #3d80b0; } /**** collapsed heading styles ****/ .ra-cp h

Hosting Multiple Domains In Tomcat

Tomcat allows us to host multiple domains in one instance, using multiple ' Host ' tags. In this article I will explain how to do it on Tomcat. This is very simple configuration using ' Host ' tags in your server.xml . A novice can also understand this configuration very easily. Before going into the details of the configuration first lets have a look at the ' Host ' tag, ' Context ' tag and ' Alias ' tags first. <Host name="domain1" appBase="[application base]" autoDeploy="[true/false]" unpackWARs="[true/false]"> <Alias>...</Alias> <Context path="" docBase="" reloadable="[true/false]"/> </Host> First lets have a look at ' Alias ' tag. This tag is used to provide aliases for your actual domain. For example you have a domain called 'domain1.com', and you want to run the same application for 'www.do

File Uploading Using Servlets, JSP and Commons File Upload API

I’ve seen many developers who are at the early stages of their career have problems with this topic and seen many posts in forums asking how to do it – File Uploading using Servlets, JSP!; this article will provide an example using Commons File Upload API. I tried to make the example as simple as possible, hope it helps those early birds. Example uses JSP to provide the pages with form where user can select the file to upload with other form fields, Commons File Upload API to process submitted form and read form fields separately, and Servlets as middle layer between JSP and Commons File Upload API, example also has ANT build script to generate the distributables. All the code can be downloaded, links to these resources are provided at the end of this post, lets get on with the example then. The flow in this example is as depicted in the following picture. As you can see, user selects the file to upload and provides normal form data as well, using "index.jsp" and submi