"Go" "Java" on whether an integer is an address pass or a value pass

Source: Internet
Author: User

Transferred from: Http://www.tuicool.com/articles/AraaQbZ

On whether an integer is an address pass or a value pass

Integer as the time to pass the argument is the address, you can refer to the following example, the program just start when the Integer Index object is locked, and call the Wait method, freed the lock resources, waiting for notify, last 5 seconds, waiting for Testobject The Notify method is called to continue execution. Everyone knows that the lock object and the object to be released must be the same, otherwise it will throw java.lang.IllegalMonitorStateException. This proves that an integer passed as an argument is an address pass, not a value pass.

PublicClassIntegersyn {   PublicStaticvoid Main (string[] args)Throws Interruptedexception { Integer index =0; Testobject A =New Testobject (index);  Synchronized (index) {   New Thread (a). Start ();  Index.wait (); } System.out.println ("End");}}ClassTestobjectImplementsRunnable { Private Integer index;  Public Testobject (Integer index) {  This.index = index;}  public  void Run () {  try {   TimeUnit.SECONDS.sleep (5);  } catch (interruptedexception e) {   E.printstacktrace ();  }  synchroniz Ed (index) {   Index.notify ();  Span class= "indent" >}}           

Then someone will ask, why do the following code two times the output is the same?

void Main (string[] args) throws interruptedexception {    0;  System. out.println (index); test (index); System. out.println (index); }void Test (Integer index) { index++; }         

The reason is simple, you can see the final value field in the integer class, stating that once the integer class is created, his value cannot be modified, and the integer is created as a new class when index++, so the result is the same when the second output!

Value

"Go" "Java" on whether an integer is an address pass or a value pass

Related Article

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.