I would highly recommend that you read my previous post about String immutability in order to understand String immutability. This will help you to understand when and where to use String, StringBuffer or StringBuilder.
As explained in my previous post, String objects are immutable i.e. once an object is created with some value, its value can never be changed. If any manipulation is done to that string, a whole new String object is created while the old one remains in the memory. This may result in wastage of precious memory. So, if large number of operations are done on a string, a large number of objects will be created in memory(one object per operation). Those String objects will be of no use and will result in wastage of memory, which is a very precious resource.
It is where the StringBuffer and StringBuilder come into play. Any number of operations can be performed on a single StringBuffer or StringBuilder object. The changes will be reflected in that single object only unlike a String object in which a new String object is created for every operation performed on a string.
As explained in my previous post, String objects are immutable i.e. once an object is created with some value, its value can never be changed. If any manipulation is done to that string, a whole new String object is created while the old one remains in the memory. This may result in wastage of precious memory. So, if large number of operations are done on a string, a large number of objects will be created in memory(one object per operation). Those String objects will be of no use and will result in wastage of memory, which is a very precious resource.
It is where the StringBuffer and StringBuilder come into play. Any number of operations can be performed on a single StringBuffer or StringBuilder object. The changes will be reflected in that single object only unlike a String object in which a new String object is created for every operation performed on a string.
- String name="xyz";
- name.toUpperCase();
The new String object is created and instantly lost as no reference variable is referencing to it.(Wastage of memory) - name=name.toUpperCase();
The old string object "xyz" is lost now as the reference variable 'name' is now referencing to new String object.(Wastage of memory)
- StringBuffer nameSb = new StringBuffer("Love");
- nameSb.append(" Java");
No new String object is created and the change is done to already available StringBuffer object(Memory Saving).
StringBuffer vs. StringBuilder
The StringBuilder class was added in Java 5. It has exactly the same API as the StringBuffer class, except StringBuilder is not thread safe(i.e. Its methods are not synchronized). Since StringBuilder is not thread safe(We'll learn more about thread safety in coming posts), it'll run faster than StringBuffer. So, use StringBuilder in place of StringBuffer whenever possible. So apart from synchronization, anything we say about StringBuilder's methods holds true for StringBuffer's methods, and vice versa. They both have almost the same methods and work identically.
Important methods in the String Class
rs(4t) lee cc (might be a way to remember the imp String methods)
- public String replace(char old, char new)
This method returns a String with the old character(first argument) replaced by the new character(second argument) in the String on which this method is invoked.String x="asasasas";
System.out.println(x.replace('a','A')); //output is "AsAsAsAs" - public String substring(int begin)
This method returns a String starting from the location passed as argument to the end of the String on which this method is invoked. Remember, the location is Zero-based,which means the first character of string is at index 0. So, if you want to have the String starting from 8th character you'll pass 7 as the argument to the method.String x="I love Java";
public String substring(int begin,int end)
System.out.println(x.substring(7)); //output is "Java"
This methos returns a String starting from the location passed as first argument upto the location passed as second argument(Remember, it is upto the second argument and not including the character at location passed as second argument).
String x="I love Java";
System.out.println(x.substring(2,6)); //output is "love" - public String toUpperCase()
This method returns the String in uppercase letters on which it is invoked.String x="I love Java";
System.out.println(x.toUpperCase()); //output is "I LOVE JAVA" - public String toLowerCase()
This method returns the String in lowercase letters on which it is invoked.String x="I love Java";
System.out.println(x.toLowerCase()); //output is "i love java" - public String trim()
This method returns a String without any leading or trailing blank spaces removed from the String on which it is invoked.String x=" I love Java ";
System.out.println(x.trim()); //output is "I love Java" - public String toString()
Every object in Java has this method. This method returns the value of the object on which it is invoked in some meaningful way. In case of String object, this method returns the value of the String.String x="I love Java";
System.out.println(x.toString()); //output is "I love Java" - public int length()
This method returns the length(including spaces between words) of String on which it is invoked.String x="I love Java";
System.out.println(x.length()); //output is "11" - public boolean equalsIgnoreCase(String s)
This method returns a boolean value(true) if the value of the String passed as argument and the value of String on which method is invoked is same irrespective of the upper or lower case. If the value is not equal, the method returns false.String x="I love Java";
System.out.println(x.equalsIgnoreCase("i love java")); //output is "true" - public boolean equals(Object o)
Every object in Java has this method. In view of String objects, it compares the string on which this method is invoked to the specified object. The result istrueif and only if the argument is notnulland is aStringobject that represents the same sequence of characters as the String object that invoked the method.String x="I love Java";
System.out.println(x.equals("i love java")); //output is "false"
System.out.println(x.equals("I love Java")); //output is "true" - public char charAt(int index)
Returns thecharvalue at the specified index. An index ranges from0tolength() - 1. The firstcharvalue of the sequence is at index0, the next at index1, and so on, as for array indexing.String x="I love Java";
System.out.println(x.charAt(2)); //output is "l" - public String concat(String s)
Concatenates the argument string s to the end of the this string which invoke the method.
If the length of the argument string is0, then thisStringobject is returned. Otherwise, a newStringobject is created, representing a character sequence that is the concatenation of the character sequence represented by thisStringobject and the character sequence represented by the argument string.
String x="I love Java";
The overloaded + and += operators perform functions similar to the concat() method.
System.out.println(x.concat(" very much")); //output is "I love Java very much"
String x="I love Java";
System.out.println(x+" very much"); //output is "I love Java very much"
String x="I love Java";
x+=" very much";
System.out.println(x); //output is "I love Java very much"
Important methods in the StringBuffer and StringBuilder Classes
a dir
- public synchronized StringBuffer append(String s)
public StringBuilder append(String s)
Appends the argument string to the character sequence of StringBuffer object on which this method is invoked.
The characters of theStringargument are appended, in order, increasing the length of this sequence by the length of the argument. Ifstrisnull, then the four characters"null"are appended.
StringBuffer sb=new StringBuffer("Neha");
System.out.println("before operation: "+sb); //output is "Neha"
sb.append(" Goley");
System.out.println("after operation: "+sb); //output is "Neha Goley"
StringBuilder sBuilder=new StringBuilder("Neha");
System.out.println("before operation: "+sb); //output is "Neha"
sBuilder.append(" Goley");
System.out.println("after operation: "+sBuilder); //output is "Neha Goley" - public synchronized StringBuffer delete(int start, int end)
public StringBuilder delete(int start, int end)
This method returns a StringBuilder/StringBuffer object and updates the value of the StringBuilder/StringBuffer object that invoked the method. It deletes the characters from the original object beginning from the first argument upto the second argument(remember, it is upto the second argument, not including the second argument position and remember that a string is always zero index based i.e. the first character is at position 0, second at position1 and so on).StringBuffer sb=new StringBuffer("0123456789");
System.out.println(sb.delete(5, 9)); //output is "012349"
StringBuilder sBuilder=new StringBuilder("0123456789");
System.out.println(sBuilder.delete(5, 9)); //output is "012349" - public StringBuilder insert(int offset, String str)
public synchronized StringBuffer insert(int offset, String str)
This method returns a StringBuffer/StringBuilder object by inserting the string passed in second argument of the method at the position(zero index based) specified in the first argument of the original object that invoked the method.StringBuffer sb=new StringBuffer("0123456789");
System.out.println(sb.insert(5, "-----")); //output is "01234-----56789"
StringBuilder sBuilder=new StringBuilder("0123456789");
System.out.println(sBuilder.insert(5, "-----")); //output is "01234-----56789" - public synchronized StringBuffer reverse()
public StringBuilder reverse()
This method returns a StringBuffer/StringBuilder object by reversing the characters sequence of the original StringBuffer/StringBuilder object that invoke this method.StringBuffer sb=new StringBuffer("Java is best");
System.out.println(sb.reverse()); //output is "tseb si avaJ"
StringBuilder sBuilder=new StringBuilder("Java is best");
System.out.println(sBuilder.reverse()); //output is "tseb si avaJ" - public String toString()
Every object in Java has this method. This method returns the value of the object on which it is invoked in some meaningful way. In case of StringBuffer/StringBuilder object, this method returns its value.StringBuffer sb=new StringBuffer("I love Java");
System.out.println(sb.toString()); //output is "I love Java"



I am very impressed to see the great work in Java programming. The article explains the difference between String, String Buffer, String Builder by quoting various example to provide ease to readers.
ReplyDelete