How to create string strings in different ways

Source: Internet
Author: User

There are many ways to create a string in Java, such as:

string s = new String ("Riqi"); String s = "Riqi";

But what is the difference between the two?

You know, in Java, the new object is actually creating an object in the stack memory that refers to a reference type that points to the heap memory, and the string object cannot be changed once it is created.

Java provides a buffer pool mechanism for string types, that is, when a string object is created using double quotation marks, the Java environment first looks for the same content string from the string buffer pool, and if it is found, it is used directly, and if not, a new string is created and added to the string buffer pool. Like what:

String S1 = "Riqi"; String s2 = "Riqi";

It can be understood that the variables S1 and S2 both point to the same string storage object in the heap memory in the string buffer pool.

Because of the mechanism of the buffer pool, it is generally more efficient to use string s = "Riqi" When a new string object is required.

How to create string strings in different ways

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.