Skip to main content

String, StringBuffer and StringBuilder in Java | Convert String to StringBuffer or StringBuilder and vice versa


What is String, StringBuilder and StrinfBuffer in java?

In this article we talk about String, StringBuffer and StringBuilder in java.

String :- 

String is class in java that represents sequence of characters, it can be word, number, special characters. String represents in Double Quotes (" ").

String is immutable in java.

What is immutable?

In simple word immutable means can not changable. it con not be replacable.

So String is immutable in java. we can not alter String object. 

So there is one question is pop up in your mind. We can still concatenate or changed String object in java so how it is immutable in Java?

Yes, we can concatenate or changed String object but every time we perform these kind of operations it creates new Object of that. See below image you can easily understand.

Lets see example of immutability of String.

Example 1 :- String demo with immutability

public class StringDemo {

    public static void main(String[] args) {
        
        String str = "Programming Blog";
        System.out.println(str.hashCode());
        
        str = "Uniquethrowdown " + str;
        System.out.println(str.hashCode());
        
    }

}

Output :-
1799821001
-965964782

In above example, first we create String str and assign value. after we concatenate str. So you can see before and after changing String it changes hashCode() value means it creates new Object of that String class.

StringBuffer And StringBuilder :-

StringBuffer and StringBuilder are like string but it is mutable class in java means we can easily changed, modify or replace.

Use StringBuffer and StringBuilder when you have lots of modification in some string our code.

StringBuffer is thread-safe in java. Means StringBuffer object are safe use for multiple threads.

StringBuilder is not thread-safe in java. StringBuilder gives no guarantee of synchronization.

These is main difference between StringBuilder and StringBuffer in java.

Lets see example of StringBuilder and StringBuffer in java.

Example 2 :- StringBuilder and StringBuffer in java

public class StringDemo {

    public static void main(String[] args) {
   
        StringBuffer buffer = new StringBuffer("Uniquethrowdown");
        System.out.println(buffer.hashCode());
        buffer = buffer.append(" Programming Blog");
        System.out.println(buffer.hashCode());
       
        StringBuilder builder = new StringBuilder("Java");
        System.out.println(builder.hashCode());
        builder = builder.reverse();
        System.out.println(builder.hashCode());
       
    }

}

Output :-
617901222
617901222
1159190947
1159190947

First we create StringBuffer object and then append string on that. but in output you can see hashCode is same before and after append operation. means when we change on StringBuffer class then it changes on same object it does not create another object like String class.

We can convert String to StringBuffer or StringBuilder in java. we can also convert StringBuilder or StringBuffer to String.

Example 3 :- Convert String to StringBuilder and StringBuffer in Java

public class StringDemo {

    public static void main(String[] args) {
        
        String str = "Programming Blog";
        
        // Convert string to StringBuffer
        StringBuffer buffer = new StringBuffer(str);
        
        // Convert string to StringBuilder
        StringBuilder builder = new StringBuilder(str);
        
        System.out.println(str);
        System.out.println(buffer);
        System.out.println(builder);
        
    }

}

Example 4 :- Convert StringBuffer or StringBuilder to String

public class StringDemo {

    public static void main(String[] args) {
        
        StringBuffer buffer = new StringBuffer("Uniquethrowdown");
        StringBuilder builder = new StringBuilder("Programming Blog");
        
        String bufferToStr = buffer.toString();
        System.out.println(bufferToStr);
        System.out.println(bufferToStr instanceof String);
        
        String builderToStr = builder.toString();
        System.out.println(builderToStr);
        System.out.println(builderToStr instanceof String);
        
    }

}

Output :-
Uniquethrowdown
true
Programming Blog
true 

We use instanceof of in above example. instanceof is used to check given object is from which class.

Refrences and images from :-

Other articles you may like.

Top FREE applications and Websites to learn Coding and Programming.
 
Java interview question and answers.

Comments

Popular posts from this blog

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...