Assign and create a new difference in String

        String s1 = new String("string");
        String s2 = new String("string");

        String s3 = "string";
        String s4 = "string";

        System.out.println(s1 == s2);      //FALSE
        System.out.println(s2.equals(s1)); //TRUE

        System.out.println(s3 == s4);      //TRUE
        System.out.println(s3.equals(s4)); //TRUE

What is the difference between creation s1ands3 ? Please let me know

In String, we only have a String object, then why does it treat this two differently. s1 and s2 have different memory addresses, and s3 and s4 have the same memory address. Why does it work based on the operator .? new

+5
source share
4 answers

String, Java, String, , . , "" ... . s3 == s4 - true.

, new String, String. s1 == s2 - false. ( new. ... .)

, equals true.


, , , Java equals, ==.

, String ==, "" String.intern. , ... - ... .

+5

s1 - String, . s3 - , . java . intern() String.

java. . flyweight . Integer.valueOf(). .

+3

JVM . String, String , JVM , , String, .

, , :

1

.

2

. , . String.

3

Instead of assigning a new object, it is simply assigned a reference to the object made in step 1. This is to save memory.

+2
source

This is because the operator newforces you to create a new String instance, and in the second case, since it Stringis an immutable class, the JVM provides you with the same String instance for both variables to save memory, since there is no chance that one of these objects will change, and the second change change (unchanged, remember?), that's fine.

0
source

All Articles