String And String Buffer

Strings and StringBuffer in Java

In this article we will be discussing about Strings and StringBuffer in Java.

String is a non-primitive data type of java, non-primitive data types are created by the programmer and the String Buffer class in Java is the same as the String class except that it is mutable, i.e. it can be changed.

Strings and StringBuffer in java

What are Strings?

String is an immutable class and its object cannot be modified after creation, but it definitely refers to other objects. They are very useful in a multithreaded environment because multiple threads cannot change the state of an object, so immutable objects are thread-safe.

String and String Buffer in java

Example:

Run

import java.util.*;

public class Main{
    public static void main(String [] args){
        //Initializing a string variable
        String str = "PrepInsta";
        System.out.println(str);
    }
}
Output:

String str = "PrepInsta"

What are String Buffers?

A string buffer is a mutable class that can be used to perform operations on a string object, such as reversing a string, concatenating a string, etc. We can modify a string without creating a new string object. The string buffer is also thread-safe.

String and String Buffer in java

Example:

Run

import java.util.*;

public class Main{
   public static void main(String[] args){
      // Initializing the object of Stringbuilder class
      StringBuffer str = new StringBuffer("Prep");

      // Giving value to the Variable using append method
      str.append("Insta");
      System.out.println(str);
   }
}
Output:

String str = "PrepInsta"

Difference Between Strings And StringBuffer

KeyStringStringBuffer
BasicString is an immutable class and its object can’t be modified after it is createdString buffer is mutable classes which can be used to do operation on string object
MethodsMethods are not synchronizedAll methods are synchronized in this class.
Memory AreaIf a String is created using constructor or method then those strings will be stored in Heap Memory as well as SringConstantPoolHeap Space
PerformanceIt is fastMultiple thread can’t access at the same time therefore it is slow

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription