Master java skills

StringBuilder

StringBuilder class is similar to StringBuffer except for the fact that it is non-synchronized (not thread-safe). So, we need to be careful while using StringBuilder class.

  1. StringBuilder objects are mutable like StringBuffer objects
  2. StringBuilder class is not thread-safe

Note -> StringBuilder class should be avoided in multithreaded applications. It can be a good choice to be used in single threaded applications since it is faster compared to StringBuffer.

StringBuilder Constructors

StringBuilder()

StringBuilder(String str)

StringBuilder(int length)

StringBuilder Example

package com.javatrainingschool;

public class StringBuilderExample {
	
	public static void main(String[] args) {
		
		StringBuilder sb = new StringBuilder("David");
		//adding a space between firstname and lastname
		sb.append(" ");
		sb.append("Miller");
		
		System.out.println("Name : " + sb);
		
		System.out.println("Length : " + sb.length());
		
		System.out.println("Index of ill : " + sb.indexOf("ill"));
		
		System.out.println("Substring : " + sb.substring(2, 7));		
	}
}

Output:

String vs StringBuffer vs StringBuilder

StringStringBufferStringBuilder
Strings are immutableStringBuffer objects are mutableStringBuilder Objects are mutable
String objects are created in String constant pool.StringBuffer objects are created in Heap memoryStringBuilder objects are created in Heap memory
String operations are slowerStringBuffer operations are faster compared to StringStringBuilder operations are even faster compared to StringBuffer because they are non synchronized
String class overrides equals() method from Object class. So, contents of two strings can be compared using equals() method.StringBuffer doesn’t override equals method and thus, two StringBuffer objects can’t be compared using equals() methodStringBuilder doesn’t override equals method and thus, two StringBuffer objects can’t be compared using equals() method