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