There are two ways in which you can create a string in Java:
String x = "abc"; String y = new String ("abc");
What is the difference between these two methods?
1. Double quotes Vs. Constructors
Answer this question in two simple code.
Example 1:
String a = "ABCD"; String B = "ABCD"; System.out.println (A = = B); TrueSystem.out.println (A.equals (b)); True
in the JVM method area , A and B point to the same string literal, and the memory reference is the same, so a==b.
when creating multiple identical string literals, only one of the same string literals is saved. This is referred to as the Dwell string (stringinterning). All constant strings in Java are automatically homed.
Example 2:
String c = new String ("ABCD"); String d = new String ("ABCD"); System.out.println (c = = d); FalseSystem.out.println (C.equals (d)); True
C and D point to two different objects in the JVM heap heap, so the C==d value is false. Different objects have different memory references.
These two scenarios are demonstrated:
2. Run-time strings reside in string interning
Even if two strings are built with a constructor (new string ("")), string residency is also performed at run time.
String c = new String ("ABCD"). Intern (); String d = new String ("ABCD"). Intern (); System.out.println (c = = d); Now TrueSystem.out.println (C.equals (d)); True
3. How to use
If you just need to create a string, you need to create the string using double quotation marks. If you need to create a new string object in the heap, consider using a constructor to create a string. Here is a constructor use case reference.
Original: http://www.programcreek.com/2014/03/create-java-string-by-double-quotes-vs-by-constructor/
string-resident reference:
http://blog.csdn.net/biaobiaoqi/article/details/6892352
http://java-performance.info/string-intern-in-java-6-7-8/
Programcreek-java the base string---"" or the new string ("")