Wednesday, July 11, 2012

Working with Strings and StringBuffer/StringBuilder

In this section we'll discuss about String as well as its creation, polemic things like "Strings are immutable" and see wthat's going on behind the scenes also StringBuffer and StringBuilder will be on focus.

Let's take a look at how the string objects are created and understand the immutability.




As you can see it prints "Book" because we don't refer the new String created to "Java - Book", so the object is in the heap however nobody refers to it.

Commom methods
Let's see common methods in action.


Pool of String

Also you can use the method intern() (String class) this way we can get the string from the pool if the string pass using the method equals().


StringBuffer and StringBuilder friends of memory

Both classes are intented to help you handle Strings without wasting memory, as we mentioned Strings are immutable and if we have to handle lots and lots of them StringBuffer and StringBuilder will help you.
The unique difference between StringBuffer and StringBuilder is StringBuilder is not thread-safe which means its methods aren't synchronized, as you can imagine StringBuilder is faster than StringBuffer.


The most import thing here is StringBuffer and StringBuilder are not immutable like String and the StringBuffer contains the synchronized methods;

No comments: