Home > Blockchain >  Java Strings - What is the difference between "Java" and new String("java")?
Java Strings - What is the difference between "Java" and new String("java")?

Time:01-08

Given this example code:

class basic {
     public static void main(String[] args) {
        String s1 = "Java";
        String s2 = new String("Java");
    }
}

Are s1 and s2 both reference variables of an object? Do those two lines of code do the same thing?

CodePudding user response:

To answer your first question:

String s1 = "Java"; may reuse an instance from the string constant pool if one is available, whereas new String("Java"); creates a new and referentially distinct instance of a String object.

Therefore, Lines 3 and 4 don't do the same thing.

Regarding your second question, lets have a look at the following code:

String s1 = "Java";
String s2 = "Java";

System.out.println(s1 == s2);      // true

s2 = new String("Java");
System.out.println(s1 == s2);      // false
System.out.println(s1.equals(s2)); // true

== on two reference types is a reference identity comparison. Two objects that are equals are not necessarily ==. Usually, it is wrong to use == on reference types, and most of the time equals need to be used instead.

CodePudding user response:

Initializing String using a new keyword String s2 = new String("Java"); creates a new object in the heap of memory. String initialized through this method is mutable means to say the value of the string can be reassigned after initialization.
Whereas, String s1 = "Java" direct String initialization using the Literal creates an object in the pooled area of memory. String created through Literal doesn’t create a new object. It just passed the reference to the earlier created object.

  •  Tags:  
  • Related