[!INDEX]

  1. Points( code + stroe + reuse +version)
  2. Code ( obj.1 + lit.2 + obj.3 + obj.1(only 1) + lit.1(0, reuse) )
  3. String s2 = new String(); everytime new, even in SCP
  4. Code - 2 diff string using same literal
  5. Disadvantages:( memory , slower, rare use)

1. Points( code + store + reuse +version)

[!important]

  1. String s1 = "rajat"; (String literal)
  2. This creates a string literal.
  3. String literals in Java are stored in a special part of memory known as the String Pool (or interned memory).
  4. If another string with the same value ("rajat") is already present in the pool, Java will reuse the existing string instead of creating a new one. This helps save memory and makes the code more efficient.
  5. 1.6= method area, 1.7 = heap area
String s1 = "rajat";
String s2 = "rajat";  // Reuses the same string from the pool

2. Code ( obj.1 + lit.2 + obj.3 + obj.1(only 1) + lit.1(0, reuse) )

public class M03 { 
    public static void main(String[] args) { 
        String s1 = new String("Rajat"); // 2 object heap , SCP 
        // create s1 name variable points rajat object in heap. 
        // another object in SCP for future reference 
        String s2 = "Amit"; // create Amit in SCP only 
        String s3 = new String( "Deepak"); // create Deepak in heap and in SCP, unique 
        String s4 = new String( "Rajat"); // create Rajat in heap and Not in SCP, already, 1 obj 
        String s5 = "Rajat"; // create 0 object, points obj Rajat in SCP only, JVM Stop refer internally 
        String s6 = "monika"; // create monika in SCP only, s5 points to it 
        String s7 = "Rajat"; // create 0 object, again points obj Rajat in SCP only, 
                // SCP will not create same name literals in it. 
                // if user create it referes to the same literals. } }

3. String s2 = new String(); everytime new, even in SCP

[!NOTE]

  1. This creates a new object of type String on the heap memory, outside of the String Pool.
  2. Even if a string with the value "rajat" already exists in the pool, the new keyword will create a completely new object in the heap memory.

4. Code - 2 diff string using same literal

String s1 = new String("rajat");
String s2 = new String("rajat");  // Two different objects in heap memory, even though they have the same content

5. Disadvantages:( memory , slower, rare use)

[!NOTE]

  1. Uses more memory because each new call creates a new object in heap memory, even if an identical string already exists.
  2. Comparatively slower because it involves additional memory allocation on the heap.
  3. Use case: You only need this approach if you specifically require two different String objects for some reason (which is rare in most typical applications).