Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Strings – What is the difference between "Java" and new String("java")?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading