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

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

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 last