String Data Type in Java

Data Type String

What is String Data type In Java ?

String is a non-primitive data type of java, non-primitive data types are created by the programmer but exceptionally String data type is predefined by the JVM i.e. Java Virtual Machine. 

Here, in the page we will discuss more about the String data type in java.


String is a Special Data type in java which is used to define a sequence of characters having a storage width equal to 2.14 Billion. In simple Language we can say that strings are the sequence of characters surrounded by double quotes (” “).

For Example : “PrepInsta”

String can be initialized by 2 different ways;-

  • By String Literal
  • By new Keyword

1. String Literals

Strings can be created by String literals by giving sequence of characters surrounded by double quotes to a variable.

For Example :

String S = “PrepInsta”

2. New Keyword

Strings can also be initialized by using new String object keyword. This new String Keyword helps the programmer to initialize the string dynamically i.e it will be initialized in the new memory space.

For Example :

String S = new String("PrepInsta")

It is Recommended to use String Literal instead of using new keyword as it helps JVM to optimize the memory allocation accordingly.

Here is an example to show the process of initialization of String Data type in Java :

import java.util.*;

public class Main{
    public static void main(String[] args){
        String s1 = "Prep";     //Initializing using String Literal

        String s2 = new String("Insta");    //Initializing using new Keyword


Prep Insta

String memory allocation in java

  • Every time a String Object is created as a literal, the String constant pool will receive the new object.
  • As a result, the initialization of the String literal can be optimized by JVM.


 String x = “prepinsta”;

Java’s immutable string

  • String objects are immutable in Java.
  • Immutable simply means unmodifiable or unchangeable.
  • A new string object must be created in order to change an existing string object’s data or state.

Note : In Java, a heap is used to store all objects. A reference variable points to an object that is either stored in the stack area or the heap area depending on whether it is contained in another object.

Prime Course Trailer

Related Banners

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