[!INDEX]
- Points( code + stroe + reuse +version)
- Code ( obj.1 + lit.2 + obj.3 + obj.1(only 1) + lit.1(0, reuse) )
- String s2 = new String(); everytime new, even in SCP
- Code - 2 diff string using same literal
- Disadvantages:( memory , slower, rare use)
1. Points( code + store + reuse +version)
[!important]
String s1 = "rajat";(String literal)- This creates a string literal.
- String literals in Java are stored in a special part of memory known as the String Pool (or interned memory).
- 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.- 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]
- This creates a new object of type
Stringon the heap memory, outside of the String Pool.- Even if a string with the value
"rajat"already exists in the pool, thenewkeyword 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]
- Uses more memory because each
newcall creates a new object in heap memory, even if an identical string already exists.- Comparatively slower because it involves additional memory allocation on the heap.
- 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).