A string variable is equal to the new one string object as long as it is assigned a value

Source: Internet
Author: User

Introduction

As soon as the string is assigned to the new object, the string variable points to the new object, and the previous object is the object that has no reference to it.


Look at the following code:

public class Example {

    String str = new String ("good");

    char[] ch = {' A ', ' B ', ' C '};

    public static void Main (String args[]) {

        Example ex = new Example ();

        Ex.change (Ex.str, ex.ch);

        System.out.print (Ex.str + "and");

        System.out.print (ex.ch);

    }

    public void Change (String str, char ch[]) {

        str = ' Test ok ';

        Ch[0] = ' g ';

    }
}

What the result output is.

I thought it would be good and ABC, because the formal parameter cannot change the value of the argument (this should be the case when the value is passed), but the correct result is good and GBC, and then it is understood that the reference is passed to the formal parameter (some data are checked, some say only value is passed in Java, no reference is passed. Some also say that there are two kinds of transmission, I also do not understand it, and then in the formal parameters of the change, the argument will also change, analogy C language pointers. So, the value of ch[0] will change, but why is the value of the string str unchanged? I think it is necessary to check the hash code of the object.

Look at the following code:

public class Example {

    String str = new String ("good");

    char[] ch = {' A ', ' B ', ' C '};

    public static void Main (String args[]) {

        Example ex = new Example ();

        Ex.change (Ex.str, ex.ch);
        
        SYSTEM.OUT.PRINTLN ("Ex str Hash" +ex.str.hashcode ());//Get Ex.str hashcode
	System.out.println ("Ex-ch-hash" + Ex.ch.hashCode ());//Obtain ex.ch hashcode

        System.out.print (ex.str + "and");

        System.out.print (ex.ch);
        
        

    }

    public void Change (String str, char ch[]) {

        str = ' Test ok ';
		
	SYSTEM.OUT.PRINTLN ("Change str hash" +str.hashcode ())//Obtain the hashcode ch[0 of str in the change method
		
        = ' g ';
				
        SYSTEM.OUT.PRINTLN ("ch hash" +ch.hashcode ());//Get hashcode} of CH in the change method


Added 4 lines to print the hash code, the hash code output is as follows:


Seeing the result, it is found that the array in the change method and the array in main are the same hashcode, indicating that the same object is modified (the object's entity is on the heap heap), so after the array is modified in the change method, The ex.ch in main will definitely be modified, too, because it is the same object on the heap.

However, the hashcode between str in the change method and ex.str in main is not the same. This means that the parameter str in the method change does not point to the object Ex.str in main, so modifying it in the changes does not affect the contents of the Ex.str object in main.

So the question is, since all references are passed to the formal parameter, why does the array point to the same object on the heap, and the string does not point to the object on the same heap?

The code above is slightly modified, as follows:

public class Example {

    String str = new String ("good");

    char[] ch = {' A ', ' B ', ' C '};

    public static void Main (String args[]) {

        Example ex = new Example ();

        Ex.change (Ex.str, ex.ch);
        
        SYSTEM.OUT.PRINTLN ("Ex str Hash" +ex.str.hashcode ());//Get Ex.str hashcode
	System.out.println ("Ex-ch-hash" + Ex.ch.hashCode ());//Obtain ex.ch hashcode

        System.out.print (ex.str + "and");

        System.out.print (ex.ch);
        
        

    }

    public void Change (String str, char ch[]) {
    	
    	System.out.println (' Change str hash ' +str.hashcode ());/Get change Methods the hashcode//<span of str
                                                            style= "color: #ff0000;" > hashcode</span>
        str = "Test OK" to print the object of the parameter str in the change method before Str is assigned a value;
	
        Ch[0] = ' g ';
		
		
        SYSTEM.OUT.PRINTLN ("ch hash" +ch.hashcode ());//Get hashcode} of CH in the change method


The output is as follows:

At this time hashcode the same.

In other words, when passing arguments, it is true that a reference is passed, but when the string is assigned again, the newly assigned string variable (reference) no longer points to the object on the original heap.

Look at the following code:

String s = "Hello";
System.out.println (S.hashcode ());
s = "World";
System.out.println (S.hashcode ());

Output results:


As soon as a value is assigned, the hashcode of the object changes, meaning that as soon as a value is assigned, it is reborn as an object instead of making changes on the original object.

After executing these lines of code, there are two objects on the heap ... One is "Hello" and one is "world". That is, when you change the contents of a string, it does not rewrite the contents of the original heap memory, but rather a new heap of memory to save the newly assigned string contents. What this mechanism looks like. Yes, it's the new one, so I think the 2nd and 3rd lines of code are equivalent:

String s = "Hello";
s = "World";
s = new String ("World");
s points to the new "Hello" object first, when a value is assigned to S (Execute line 2nd), s This reference variable points to the new heap memory object "World", and the previous "Hello" object becomes an object that has no reference to it, and I think it will soon be GC.

So, come to a conclusion: as long as the string assignment is equivalent to a new object, the string variable points to the new object, before the object is no reference to the object.


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.