Square CSS

Monday, October 8, 2018

String vs StringBuffer vs StringBuilder

Let's have some basic idea about String, StringBuffer and StringBuilder.

String in Java

A string is immutable in Java. String class represent character strings, i.e. string class is implemented with the char array. We can create a string in two ways :

  
  String str1 = "playjavatutorials";
  String str2 = new String("playjavatutorials"); 


When a string is created using double quotes it checks for the same value in the string pool. 
If the value already exists in the string pool then it returns the reference else creates it's object and then places it in the string pool. In this way, JVM saves lots of memory by using the same string at many places and threads.

When a string is created with the new operator then it explicitly creates a string in the heap memory.

The string is a final class with its all fields as final except for 'private int hash'.

String overrides equals() and hashCode() method to verify if given two strings are same or not. The equals() method is case sensitive so if case-sensitive checks are not required then equalsIgnoreCase() method should be used. 

StringBuffer in Java

A StringBuffer is like String but it can be modified because of its mutable nature. They are thread-safe and can be easily used in a multithreaded environment.

It has two important methods append() and insert().

The append("x") function appends "x" at the end of existing StringBuffer.
The insert(5, "x") function inserts the string "x" at the provided index of existing StringBuffer. In this case, it is 5.

  
   StringBuffer sb=new StringBuffer("Initial");  //Initial
   sb.append("Appended");  //InitialAppended
   sb.insert(7, "Inserted");   //InitialInsertedAppended         


To convert a StringBuffer to String we use toString() method. 


  String str = sb.toString();


StringBuilder in Java

Unlike String, StringBuilder is mutable in nature. The API of this class is compatible with StringBuffer except that the StringBuilder is unsafe in a multithreaded environment. It is not synchronized so should it should not be used where thread safety is of prime concern.



The difference: String vs StringBuffer vs StringBuilder

The main difference between String and StringBuffer/StringBuilder is the immutability. A string is immutable whereas StringBuffer/StringBuilder is mutable.
StringBuilder is non-synchronous in nature whereas StringBuffer can be used in a multithreaded environment. 


☛ Next >> If-Else Statement
                      
In Java, if-else statements are used to run codes on basis of boolean con ...

No comments:

Post a Comment

Some Algorithms

Algorithm: Tower of Hanoi

Tower of Hanoi consists of three towers called as pegs with n number of rings. Rings are of different size.  Conditions to be fulfill...

Popular Posts