Pages

Efficient way to build strings | Java

In java, the string is a immutable data type. Immutable is something that could not be modified once it is created. There are immutable data objects in other languages also, eg tuples in python.

Now lets get to the point.
I used to do the straight way to concat strings in java with the += operator. Even though I have to build a string using long algorithms. I even used the same way for my document parser in the previous, which I may soon re-implement. The point is that, every time I add another character to a string, the original string is destroyed, and an entirely string is created with the character added in the original string. Now the overhead of object creation may not be huge for a few string concatenation but say if our algorithm is such that we are performing 50 or 100 or thousands of strings additions or subtractions, then it has a huge impact. The solution is to use the StringBuilder object.

What this class does is, it provide append, delete kind of methods. It does not create new string objects on every append or delete and thus the object creation overhead is removed. It creates an string object only when called the toString() method.

Here is an example.
        StringBuilder sb = new StringBuilder();
        sb.append("rajana");
        sb.deleteCharAt(sb.length()-1);
        sb.append(" upadhyay");
        System.out.println(sb.toString());

1 comment:

  1. This blog is really helpful. I appreciate you sharing this post with us. Learning Java can undoubtedly open doors to numerous opportunities and pave the way for a successful career in the ever-expanding world of technology. Enroll in Java classes in Solapur to upskill yourself.

    ReplyDelete

If you like to say anything (good/bad), Please do not hesitate...