Sunday, July 27, 2014

String Handling in Java

String represents a sequence of characters. It has fixed length of character sequence. Once a string object has been created than we can't change the character that comprise that string. It is immutable. This allows String to be shared. String object can be instantiated like any other object
String s=new String();
This creates an empty string by calling default constructor.
char c[]={'a','b','d'};
String s=new String(c);
In this case string s points to the character array "abd".
StringBuffer
This represents growable and writable character sequence. It is mutable in nature. StringBuffer are safe to be used by multiple thread as they are synchronized but this brings performance penalty. It defines 3-constructor:

  • StringBuffer(); //initial capacity of 16 characters
  • StringBuffer(int size); //The initial size
  • StringBuffer(String str);
The following table describes the various important string search methods.
int indexOf(int ch)Returns the first occurrence of the specified character.
int lastIndexOf(int ch)Returns last occurrence of the specified character.
boolean contains(CharSequence s)Returns true if the string contains the specified character sequence.
String replace(char oldChar,char newChar)Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String substring(int startIndex)return a subtring,and startindex specifies the index at which substring will begin.
String trim()This will removed the leading and trailing whitespace
String concat(String str)It will append the string str at the end.

StringBuilder
StringBuilder class is introduced in Java 5.0 version. This class is an alternative to the existing StringBuffer class. If you look into the operations of the both the classes, there is no difference. The only difference between StringBuilder and StringBuffer is that StringBuilder class is not synchronized so it gives better performance. Whenever there are no threading issues, its preferable to use StringBuilder. StringBuffer class can be replaced by StringBuilder with a simple search and replace with no compilation issue.

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete