Programcreek-java the base string---"" or the new string ("")

Source: Internet
Author: User

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 ("")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.