In Java, String str = new String ("ABC") creates several objects __java

Source: Internet
Author: User
The answer is two, and now let's be specific:
string s = new String ("abc");
First we need to understand two concepts, referencing variables and objects, and objects are generally created in the heap by new, and S is just a reference variable.

All strings are string objects, because of the large use of string literals, in Java in order to save time, in the compilation phase, the string will be placed in a constant pool, the advantage of a constant pool is that you can combine the same string, occupy a space, we can use = = Determine if the two reference variable points to an address that is an object.

The ' = = ' in 1.Java:

1 if it is 8 basic types, = = Returns true;

String S1 = "abc";
 String s2 = "abc";
System.out.println (S1==S2);/return true</span>
2 If it is a reference type, = = Compares two variables to point to the same memory.

string S1 = new String ("abc");
String s2 = new String ("abc");
System.out.println (S1==S2);/return false</span>

2.String s = new string ("abc") is actually "ABC" itself is an object in a constant pool, and when you run the new string (), copy the constant pool, the string "abc" in pools, to the heap and give the application of this object to S. So we created two string objects, one in the pool and one in the heap. Look at the program below and create a few objects.
public class Demo03 {public
    static void Main (string[] args) {
        //TODO auto-generated method stub
        String S1 = New String ("abc");
        String s2 = new String ("abc");
        if (S1 = = s2) {//will not execute the statement}
       System.out.println ("created an object in the heap");

    }
        else{
        System.out.println ("two objects created in the heap");}}
Two objects were created in the heap, but there was one object in the text pool, so three objects were created

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.