Header Ads

String and String Buffer

 



Strings in java are considered as String Objects. Java has two types string. i.e. Mutable and Immutable String.

Mutable String: It can be modified in terms of length and content. Ex. StringBuffer class
Immutable String: It cannot be modified in terms of length and content. Ex. String class

String class is called as Immutable because any operation on string results into new String object by implicit execution of new String() .

JVM manages separate memory (specialized heap memory) called as string constant pool for efficient memory utilization. In this part of memory, only string objects are stored. JVM monitors string constant pool to check whether new string object to be created is already present on the string constant pool. If it is present, then new String object will not be created only references are manipulated.

Strings are very important part of the programming language as they are used to process long textual/symbolic information. For example, when we visit a bank to open an account then we are asked for information such as name, address. The information we provide is in the form of ordered sequence of characters and symbols. The ordered sequence of characters and symbols is known as String.

Declaring and Constructing a String:

Strings represent a sequence of characters a java string is an instantiated object of the string class. Strings may be declared and created as follows:

String stringName;
stringName = new String("Java");

Or

String stringName = new String("Java");

Or

String stringName="java";

Note: stringName is actually a reference to the String object.

Methods of Strings:

The String class defines a number of methods that allows us to accomplish a variety of string manipulation tasks. The below table lists some of the most commonly used string methods and their tasks.

String methods

Example:

Code

class StringEx 
{ 
 public static void main(String args[]) { 
   String s1 = "India"; 
   System.out.println("s1 = "+s1); 
   int len=s1.length(); 
   System.out.println("Length = "+len); 
   String s2=s1.toLowerCase(); 
   System.out.println("Lower Case of s1 = "+s2); 
   s2=s1.toUpperCase(); 
   System.out.println("Upper Case of s1 = "+s2); 
   String s3=s1.replace('i','b'); 
   System.out.println("Upper Case of s1 = "+s3); 
   System.out.println("s1 equals s2 ="+s1.equals(s2)); 
   System.out.println("s1 equals s2 = +s1.equalsIgnoreCase(s2)); 

   System.out.println("s1 compares s2 = "+s1.compareTo(s2)); 
   System.out.println("s2 compares s1="+s2.compareTo(s1)); 
   System.out.println("Concatenate s1 with string = "+s1.concat(" is Great")); 
   System.out.println("Substring of sl = " +s1.substring(3)); 
   System.out.println("Substring of sl="+s1.substring(2,5)); 
   System.out.println("Index of i in s1="+s1.indexOf('i')); 
 } 
} 
Output:
s1 = India
Length = 5
Lower Case of s1 = india
Upper Case of s1 = INDIA
Upper Case of s1 = Indba
s1 equals s2 = false
s1 equals s2 = true
s1 compares s2 = 32
s2 compares s1 = -32
Concatenate s1 with string = India is Great
Substring of s1 = ia
Substring of s1 = dia
Index of i in s1 = 3

String Buffer class:

The StringBuffer is a class which is alternative to the String class. But StringBuffer class is more flexible to use than the String class. StringBuffer creates strings of flexible length that can be modified in terms of both length and content. but in case of String class once the string is defined then it remains fixed. i.e. String creates strings of fixed length, we can insert characters and substrings in the middle of a string, or append another string to the end. The StringBuffer and the StringBuilder are almost one and the same. The StringBuilder or StringBuffer have three constructors and 30 methods.

Following are some simple methods used for StringBuffer 

String buffer method

These methods can be illustrated with the help of following Java programs-

Example- Write a Java program that uses the length() and capacity () methods of StringBuffer class.

Solution:

Code

public class StringBuffDemo1{ 
  public static void main(String args[]) 
  { 
    StringBuffer str=new StringBuffer("Java"); 
    System.out.println("The String Buffer is "+str); 
    System.out.println("The length is "+str.length()); 
    System.out.println("The capacity is"+str.capacity()); 
  }
}
Output

The String Buffer is Java
The length is 4
The capacity is 20

Program Explanation: Using the StringBuffer/StringBuilder class, we can create a buffer of characters. The length() function returns the number of characters in the string and the capacity function returns the number of characters in the string +16 additional characters.

Java StringBuilder class - Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

Constructors of StringBuilder class

1.StringBuilder(): creates an empty string Builder with the initial capacity of 16.
2.StringBuilder(String str): creates a string Builder with the specified string.
3.StringBuilder(int length): creates an empty string Builder with the specified capacity as length.

Important methods of StringBuilder class

1. public StringBuilder append(String s) - It 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 StringBuilder insert(int offset, String s) – It 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 StringBuilder replace(int startIndex, int endIndex, String str) - It is used to replace the string from specified startIndex and endIndex.

4. public StringBuilder delete(int startIndex, int endIndex) - It is used to delete the string from specified startIndex and endIndex.

5. public StringBuilder reverse()-It is used to reverse the string.

6. public int capacity()- It is used to return the current capacity.

7. public void ensureCapacity(int minimumCapacity) - It is used to ensure the capacity at least equal to the given minimum.

8. public char charAt(int index) - It is used to return the character at the specified position.

9. public int length() It is used to return the length of the string i.e. total number of characters.

10. public String substring(int beginIndex) – It is used to return the substring from the specified beginIndex.   

11. public String substring(int beginIndex, int endIndex) - It is used to return the substring from the specified   beginIndex and endIndex.

Java StringBuilder Examples

1) StringBuilder append() method- It concatenates the given argument with this string.

Code

class A{ 
   public static void main(String args[]){ 
     StringBuilder sb new StringBuilder("Hello");
     sb.append("Java");//now original string is changed 
     System.out.println(sb);//prints Hello Java 
   }
}
2) StringBuilder insert() method - It inserts the given string with this string at the given position. 

Code

class A{ 
 public static void main(String args[]){ 
   StringBuilder sb-new StringBuilder("Hello "); 
   sb.insert(1,"Java");//now original string is changed 
   System.out.println(sb); //prints HJavaello 
  }
}
3) StringBuilder replace() method - It replaces given string from the specified beginIndex and endIndex.

Code

class A{ 
   public static void main(String args[]){ 
      StringBuilder sb=new StringBuilder("Hello"); 
      sb.replace(1,3,"Java"); 
      System.out.println(sb);//prints HJavalo 
   } 
} 
4) StringBuilder delete() method - It deletes the string from the specified beginIndex to endIndex.

Code

class A{ 
   public static void main(String args[]){ 
     StringBuilder sb=new StringBuilder("Hello"); 
     sb.delete(1,3); 
     System.out.println(sb);//prints Hlo 
  } 
}
5) StringBuilder reverse() method - It reverses the current string.

Code

class A{ 
  public static void main(String args[]) { 
     StringBuilder sb-new StringBuilder("Hello"); 
     sb.reverse(); 
     System.out.println(sb);//prints olleH 
  } 
}
6) StringBuilder capacity() method -The capacity() method of StringBuilder class returns the current capacity of the Builder. Default capacity of the Builder is 16. If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. Ex if your current capacity is 16, it will be (16*2)+2=34.

Code

class A{ 
 public static void main(String args[]){ 
   StringBuilder sb-newStringBuilder();
   System.out.println(sb.capacity());//default 16 
   sb.append("Hello"); 
   System.out.println(sb.capacity());//now 16
   sb.append("java is my favourite language"); 
   System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 
   }
}
7) StringBuilder ensureCapacity() method - It ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

Code

class A{ 
   public static void main(String args[]){ 
     StringBuilder sb-new StringBuilder(); 
     System.out.println(sb.capacity());//default 16 
     sb.append("Hello"); 
     System.out.println(sb.capacity());//now 16 
     sb.append("java is my favourite language"); 
     System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2 
     sb.ensureCapacity(10);//now no change 
     System.out.println(sb.capacity());//now 34 
     sb.ensureCapacity(50);//now (34*2)+2 
     System.out.println(sb.capacity());//now 70 
  }
}
Difference between String and StringBuffer?

difference between string and string buffer

Difference between StringBuffer and StringBuilder?

All the things between StringBuffer and StringBuilder are same only difference is StringBuffer is synchronized and StringBuilder is not synchronized. synchronized means one thread is allow at a time so it thread safe. Not synchronized means multiple threads are allow at a time so it not thread safe. 

difference between string buffer and string builder


No comments

Powered by Blogger.