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

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

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 ...