Tuesday, 14 January 2014

String Class and StringBuffer Class

String
Generally string is a sequence of characters. But in java, string is an object. String class is used to create string object.

How to create String object?
There are two ways to create String object:
  • By string literal
  • By new keyword
  1. String literal
String literal is created by double quote.For Example:
String s="Hello"; 
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.For example:
String s1="Welcome"; 
String s2="Welcome";//no new object will be created 

In the above example only one object will be created.First time JVM will find no string object with the name "Welcome" in string constant pool,so it will create a new object.Second time it will find the string with the name "Welcome" in string constant pool,so it will not create new object whether will return the reference to the same instance.
String objects are stored in a special memory area known as string constant pool inside the Heap memory.

Why java uses concept of string literal?
  • To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).
  • String objects are immutable. Immutable simply means unmodifiable or unchangeable.
  • Once string object is created its data or state can't be changed but a new string object is created.
Methods of String class
java.lang.String class provides a lot of methods to work on string. Some of them are as follows: 
  1. public boolean equals(Object anObject):     Compares this string to the specified object.
  2. public boolean equalsIgnoreCase(String another):    Compares this String to another String, ignoring case.
  3. public String concat(String str):     Concatenates the specified string to the end of this string.
  4. public int compareTo(String str):     Compares two strings and returns int
  5. public int compareToIgnoreCase(String str):    Compares two strings, ignoring case differences.
  6. public String substring(int beginIndex):    Returns a new string that is a substring of this string.
  7. public String substring(int beginIndex,int endIndex):    Returns a new string that is a substring of this string.
  8. public String toUpperCase():    Converts all of the characters in this String to upper case
  9. public String toLowerCase():    Converts all of the characters in this String to lower case.
  10. public String trim():    Returns a copy of the string, with leading and trailing whitespace omitted.
  11. public boolean startsWith(String prefix):    Tests if this string starts with the specified prefix.
  12. public boolean endsWith(String suffix):    Tests if this string ends with the specified suffix.
  13. public char charAt(int index):    Returns the char value at the specified index.
  14. public int length():     Returns the length of this string.
  15. public String intern():    Returns a canonical representation for the string object.
StringBuffer class:

  • The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class is same as String except it is mutable i.e. it can be changed.
  • StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously .So it is safe and will result in an order.

Commonly used Constructors of StringBuffer class:


StringBuffer(): creates an empty string buffer with the initial capacity of 16.
StringBuffer(String str): creates a string buffer with the specified string.
StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length.

Commonly used methods of StringBuffer class:
  1. public synchronized StringBuffer append(String s): is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
  2. public synchronized StringBuffer insert(int offset, String s): is used to insert the specified string with this string at the specified position. The insert() method is overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
  3. public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is used to replace the string from specified startIndex and endIndex.
  4. public synchronized StringBuffer delete(int startIndex, int endIndex): is used to delete the string from specified startIndex and endIndex.
  5. public synchronized StringBuffer reverse(): is used to reverse the string.
  6. public int capacity(): is used to return the current capacity.
  7. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least equal to the given minimum.
  8. public char charAt(int index): is used to return the character at the specified position.
  9. public int length(): is used to return the length of the string i.e. total number of characters.
  10. public String substring(int beginIndex): is used to return the substring from the specified beginIndex.
  11. public String substring(int beginIndex, int endIndex): is used to return the substring from the specified beginIndex and endIndex.

What is mutable string?

A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string.

Example of StringBuffer class by append() method

The append() method concatenates the given argument with this string.
class A{ 
public static void main(String args[]){ 
 
StringBuffer sb=new StringBuffer("Hello "); 
sb.append("Java");//now original string is changed 
 
System.out.println(sb);//prints Hello Java 

No comments:

Post a Comment