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
s1
s3
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
new
String, Java, String, , . , "" ... . s3 == s4 - true.
String
s3 == s4
true
, new String, String. s1 == s2 - false. ( new. ... .)
s1 == s2
false
, equals true.
equals
, , , Java equals, ==.
==
, String ==, "" String.intern. , ... - ... .
String.intern
s1 - String, . s3 - , . java . intern() String.
java. . flyweight . Integer.valueOf(). .
Integer.valueOf()
JVM . String, String , JVM , , String, .
JVM
, , :
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.
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.