The question of passing Java values is illustrated in an intuitive way. If you have a high opinion, please make an axe!

Source: Internet
Author: User

For the differences between the two code segments and the results, use the code to illustrate the memory and execution process.
Thank you!

    public class PassAddr {          public static void main(String[] args) {              String s=new String("old");  //1            method(s);  //3            System.out.println(s);          }          static void method(String str){              str=new String("new");  //2        }      }  

The output result is: Old.

Public class t {public static void main (string [] ARGs) {string [] arr = new string [2]; arr [0] = "old_0 "; arr [1] = "old_1"; // 11/* arr [0] = new string ("old_0"); arr [1] = new string ("old_1 "); // 11 similarly */method (ARR); // 14 system. out. println (ARR [0] + ";" + arr [1]);} static void method (string [] A) {// 12 A [0] = "new_0 "; A [1] = "new_1"; // 13 }}

 

This output is: new_0; new_1
-------------------------------------------

I thought about the problem for a long time. Next, I hope you will be right!
==========================================

String: // at 1:

// 2:

// 3:

Because the method call has been completed, the STR Temporary Variable disappears in the stack, S is still 0x001, and the object new string ("old") at the address is not passive; the output result is old;

--------------------------------------------------- Stubborn split line ------------------------------------------------------

// Memory status at 11:

// 12 points:

// Memory status at 13:

At this time, the values of a [0] And a [1] are changed, which is actually the corresponding value of arr. Finally, the result is displayed. // 14

So the result changes.

This plot is intuitive.

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.