String In Java,StringBuffer vs StringBuilder

Today we will understand what is String in Java , and then we will understand difference in String vs StringBuffer vs StringBuilder in java.

String :

String is a class in java , which is available in java.lang package ,java.lang.String in java is defined as , an object that represents sequence of characters.In java , objects of String are immutable which means a constant , and can not be changed once created.

String class in java provide various important method like :

toUpperCase()

convert String to upper case.

toLowerCase()

convert String to lower case.

length()

to check length of String.

concat()

to concatenate two String .

split()

to split String.

and many other methods ,each method is used to perform some operation on String type object.

check below program where we are creating String type variable using different ways :

public class StringDemo {
	public static void main(String[] args) {
		String websiteUrl="https://www.crtr4u.com";
		String subject=new String("java programming");
		char charArray[] = {'P','Q','R','S','T'};	
		String strFromCharArray= new String(charArray);
		byte[] byteArray= {70,71,72};
		String stringFromByteArray=new String(byteArray);
		
		System.out.println(stringFromByteArray);		
		System.out.println(strFromCharArray);
		System.out.println(subject);	
		System.out.println(websiteUrl);
	}
}

Output of above program :

FGH
PQRST
java programming
https://www.crtr4u.com

In below program ,we are Performing different operations on String using inbuilt methods :

package com.suv.string;
public class StringDemo2 {
 public static void main(String[] args) {
	String websiteUrl="https://www.crtr4u.com/2023/01/string-in-java.html";
	String name="Swapnil V";
	String []splittedArray=websiteUrl.split("\\.");
				
	for(String str: splittedArray) {
		System.out.println(str);
	}			
		System.out.println(name.toLowerCase());
		System.out.println(name.toUpperCase());
		System.out.println(name.length());
	}
}

Output of above program:

https://www
crtr4u
com/2023/01/string-in-java
html
swapnil v
SWAPNIL V
9

More About String in Java :

The java.lang.String class implements Serializable,Comparable and CharSequence interfaces.
Immutable String in Java : immutable means unmodifiable or unchangeable , String object in java is immutable.

Since String is immutable in Java,whenever we do String manipulation like concatenation, sub-string, etc.it generates a new String.So Java has provided StringBuffer and StringBuilder classes that should be used for String manipulation.

Important String related point for interview of java programmer :

String is one of the most widely used classes in Java,String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer and StringBuilder classes provide methods to manipulate strings.

StringBuffer vs StringBuilder

In StringBuffers all public methods are synchronized. StringBuffer provides Thread safety but at a performance cost , it reduce performance.In most of the scenarios, we don’t use String in a multithreaded environment. So Java 1.5 introduced a new class StringBuilder,which is similar to StringBuffer except for thread-safety and synchronization.StringBuffer has some extra methods such as substring, length, capacity, trimToSize, etc.However,these are not required since you have all these present in String too.That’s why these methods were never implemented in the StringBuilder class.StringBuffer was introduced in Java 1.0 whereas StringBuilder class was introduced in Java 1.5 after looking at shortcomings of StringBuffer.

StringBuffer and StringBuilder are mutable objects in Java and they provide append(), insert(), delete(), and substring() methods for String manipulation.StringBuffer is thread-safe and synchronized whereas StringBuilder is not.That’s why StringBuilder is faster than StringBuffer.For String manipulations in a non-multi threaded environment, we should use StringBuilder , and in multithreaded environment always use StringBuffer class.

StringBuilder performs better than StringBuffer even in the case of a single-threaded environment. This difference in performance can be caused by synchronization in StringBuffer methods.If you are in a single-threaded environment or don’t care about thread safety, then you should use StringBuilder. Otherwise, use StringBuffer for thread-safe operations.

Below Program Prove that String is immutable and String Builder is Mutable :

public class StringPractice {
 public static void main(String[] args) {
  String name="Swapnil";
   System.out.println("original name "+name);	
   System.out.println("modifying name as "+name.concat("Vyawhare"));	
   System.out.println("****final name using String : "+name);			
	
   StringBuilder name2=new StringBuilder("Swapnil");	
    System.out.println("original name "+name2);	
    System.out.println("modifying name as "+name2.append("Vyawhare"));	
    System.out.println("****final name using StringBuilder :"+name2);
	
    StringBuffer name3=new StringBuffer("Swapnil");	
	System.out.println("original name "+name3);	
	System.out.println("modifying name as "+name3.append("Vyawhare"));	
	System.out.println("****final name using StringBuffer :"+name3);
	}
}

Output :

original name Swapnil
modifying name as SwapnilVyawhare
****final name using String : Swapnil
original name Swapnil
modifying name as SwapnilVyawhare
****final name using StringBuilder :SwapnilVyawhare
original name Swapnil
modifying name as SwapnilVyawhare
****final name using StringBuffer :SwapnilVyawhare

Explanation :

In String class we have a concat() method to concatenate two String ,and in StringBuilder,StringBuffer classes we have append() method.In above example ,for String type variable final name is not changed after concatenation , but for StringBuilder and StringBuffer final name is modified,which proves that String is immutable and StringBuilder and StringBuffer are mutable.

Happy Learning and have a great day ahead.

Leave a Reply

Your email address will not be published. Required fields are marked *