Category Archives: String

Java: StringBuilder Class & Examples


Java StringBuilder is used to create a mutable String object. It’s introduced in JDK 1.5. It’s similar to StringBuffer class the only difference is non-synchronized and no thread-safe.

See Also: String Vs StringBuffer Vs StringBuilder

Constructors of StringBuilder class

Constructor Description
StringBuilder() creates an empty string Builder with the default initial capacity of 16.
StringBuilder(String str) creates a string Builder with the given string.
StringBuilder(int length) creates an empty string Builder with the given capacity as length.

Methods of StringBuilder class

Method Description 
public StringBuilder append(String s) Append the specified string with current string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.
public StringBuilder insert(int offset, String s) 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.
public StringBuilder replace(int startIndex, int endIndex, String str) Replace the string from the specified startIndex and endIndex.
public StringBuilder delete(int startIndex, int endIndex) Delete the string from the specified startIndex and endIndex.
public StringBuilder reverse() Reverse the string.
public int capacity() Return the current capacity of String builder.
public void ensureCapacity(int minimumCapacity) Ensure the capacity at least equal to the given minimum then only increase capacity.
public char charAt(int index) Return the character at the specified index position.
public int length() return the total count of the characters in string.
public String substring(int startIndex) is used to return the substring from the specified startIndex.
public String substring(int startIndex, int endIndex) is used to return the substring from the specified startIndex and endIndex.

Example: StringBuilder append() method

Java StringBuilder append() method used to concatenates the given argument with this string.

StringBuilder sb=new StringBuilder("Facing Issues On ");
sb.append("IT");//Original String will change
System.out.println(sb);//new string "Facing Issues On IT"

Example: StringBuilder insert() method

Java StringBuilder insert() method used to insert the given string at the given position.

StringBuilder sb=new StringBuilder("Facing On IT");
sb.insert(6," Issues ");//insert string on 6th position
System.out.println(sb);//new string "Facing Issues On IT"

Example: StringBuilder replace() method

Java StringBuilder replace() method used to replaces the given string from the specified startIndex and endIndex.

StringBuilder sb=new StringBuilder("Facing Saurabh On IT");
sb.replace(7,14,"Issues");//replace saurabh with  issues
System.out.println(sb);//new string "Facing Issues On IT"

Example: StringBuilder delete() method

Java StringBuilder delete() method use to deletes the string from the specified startIndex to endIndex..

StringBuilder sb=new StringBuilder("Facing Saurabh On IT");
sb.delete(7,14);//delete saurabh
System.out.println(sb);//new string "Facing  On IT"

Example: StringBuilder reverse() method

Java StringBuilder reverse() method used to reverses the current string.

StringBuilder sb=new StringBuilder("Facing Saurabh On IT");
sb.reverse();
System.out.println(sb);//new string "TI no seussI gnicaF"

See Also: Java: Ways to reverse String

Example: StringBuilder capacity() method

Java StringBuilder capacity() method use to returns the current capacity of the Builder. The default capacity of the Builder is 16. If the number of the character increases from its current capacity, it increases the capacity by (oldcapacity2)+2. For example, Suppose your current capacity is 16, then the next capacity will be (162)+2=34.

StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Facing Issues On IT");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (old_capacity*2)+2
sb.append("Learn from Others Experinces");
System.out.println(sb.capacity()); //now (34*2)+2=70 i.e (old_capacity*2)+2

Example: StringBuilder ensureCapacity() method

Java StringBuilder ensureCapacity() method use to ensures that the given capacity is the minimum to the current capacity. If it is greater than the ensure capacity, it increases the capacity by (oldcapacity2)+2. For example, Suppose your current capacity is 16, then the next capacity will be (162)+2=34.

StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.ensureCapacity(40);//Now Capacity will increase when reach to 40
sb.append("Facing Issues On IT");
System.out.println(sb.capacity());//because of ensure capacity capacity will 40 only
sb.append("Learn from Others Experinces");
System.out.println(sb.capacity()); //now (40*2)+2=82 i.e (oldcapacity*2)+2

 

How to reverse String in Java?


In java, we can reverse String in java by so many ways as given below:

  1. StringBuffer
  2. StringBuilder
  3. Character Iteration

Reverse String in Java: By StringBuffer

public class ReverseStringExample1 {
public static String reverseString(String str){
    StringBuffer sb=new StringBuffer(str);
//String buffer in-built method
			sb.reverse();
    return sb.toString();
}
}

Reverse String in Java: By StringBuilder

public class ReverseStringExample2 {
public static String reverseString(String str){
    StringBuilder sb=new StringBuilder(str);
	//String builder in-built method
			sb.reverse();
    return sb.toString();
}
}

Reverse String in Java: By Character Iteration

public class ReverseStringExample3 {
public static String reverseString(String str){
    char ch[]=str.toCharArray();
    String rev="";
    //run loop in reverse order for each character
    for(int i=ch.length-1;i>=0;i--){
        rev+=ch[i]; //append characters
    }
    return rev;
}
}

Complete Example: Reverse String In Java

Here consolidated all the ways to reverse String in Java.

public class TestStringInJava {
public static void main(String[] args) {
     System.out.println(ReverseStringExample1.reverseString("My Name is Saurabh."));
     System.out.println(ReverseStringExample2.reverseString("Facing Issues on IT"));
     System.out.println(ReverseStringExample3.reverseString("Learn From Others Experinces"));
    }
}
}

Output

.hbaruaS si emaN yM
TI no seussI gnicaF
secnirepxE srehtO morF nraeL

 

Java: String Vs StringBuffer Vs StringBuilder


String in Java

A String class represents an array of characters.

String Instance Creation
String instance can be created in two ways:

  • By assigning as Literals
    String title = "Facing Issues On IT";
  • By using the new keyword
    String title = new ("Facing Issues On IT");

Points to Remember for Java String

  • The string class is immutable in Java, so it’s easy to share it across different threads or functions.
  • When you create a String using double quotes, it first looks for the String with the same value in the JVM string pool, if match found it returns the reference else it creates the String object and then places it in the JVM String pool. This way JVM saves a lot of space by using the same String in different threads. But if a new operator is used, it will always explicitly creates a new String in the heap memory.
  • + operator overloading is used to concatenating two strings. Although internally it uses StringBuffer to perform this action.
  • String overrides equals() and hashCode() methods, two Strings are equal only if they have the same characters in the same order. Note that equals() method is case sensitive, so if you are not looking for case sensitive checks, you should use equalsIgnoreCase() method.
  • String value represents a string in the UTF-16 format.
  • String is a final/immutable class with all the fields as final except “private int hash”. This field contains the hashCode() function value and created only when the hashCode() method is called and then cached in this field. Furthermore, the hash is generated using the final fields of String class with some calculations, so every time hashCode() method is called, it will result in the same output. For the caller, it’s like calculations are happening every time but internally it’s cached in the hash field.

Why StringBuffer & StringBuilder?

The string class is immutable in java i.e whenever we do any manipulation in String like concatenation, substring, reverse, etc. always generate a new string and discard older String for garbage collection.

That’s the reason only Java introduced StringBuffer in JDK 1.4 and StringBuilder in JDK 1.5.

StringBuffer and StringBuilder are mutable objects and provide append(), insert(), delete() and substring() methods for String manipulation.

StringBuffer vs StringBuilder

Apart from similarities, Java StringBuffer and StringBuilder having differences:

  • StringBuffer is thread-safe because all of its methods are synchronized but the main disadvantage is performance.

Note: If you are working on a single-threaded environment go with StringBuilder and in a multithreaded environment use StringBuffer. In general scenarios for string manipulation, StringBuilder is better suited than StringBuffer because String buffer is synchronized.

String vs StringBuffer vs StringBuilder

String StringBuffer StringBuilder
Immutable Mutable Mutable
Legacy JDK 1.4 JDK 1.5
Thread Safe Thread Safe No Thread Safe
Synchronized Synchronized Not Synchronized
Performance slow in manipulation Performance slow in manipulation Performance faster in manipulation
String Concat (+) uses StringBuffer and StringBuilder internally NA NA
See Also: String Class Examples See Also: StringBuffer Examples See Also: StringBuilder Examples