Two ways to initialize string in Java

Source: Internet
Author: User

Transferred from: http://www.diybl.com/course/3_program/java/javajs/2007104/75886.html
The string may be an object that appears in any programming language, and there are two most common ways to create and initialize a string object in Java:
String Str=new string ("XXX");
String str= "XXX";

The two seem to be the same, in fact there is a big difference.
The former is the standard method of object creation in Java, and the objects created will be placed directly into the heap, and a new object will be created for each call, and the latter will create an object reference variable str in the stack, and then see if there is "xxx" in the stack, and if not, store "xxx" in the stack. and makes the reference variable str point to it, and if it already has "XXX", direct str to it. This makes full use of the data sharing advantages of the stack, and of course it can be a trap where objects are likely not created, but point to a previously created object, and the new () method guarantees that a new object is created each time.
The following code shows the difference:

Java code
  1. Public class Main {
  2. /** *//** 
  3. * @param args the command line arguments
  4. */
  5. public static void Main (string[] args) {
  6. String stra = "abc";
  7. String StrB = "abc";
  8. String Straa = new String ("abc");
  9. String strbb = new String ("abc");
  10. System.out.println (Stra = = StrB);
  11. System.out.println (Straa = = STRBB);
  12. }
  13. }


Output Result:
True
False

Two ways to initialize string in Java

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.