Hi All I have come across a program in JavaBeat Mock exams which I have quoted below. As per K&B text book(Pg 203), passing of object reference variables to a method that modifies the object state will modify the original state of the object. But the program below is giving a different output. Take a look...
The output I was expecting was "java.awt.Button null" while the program outputs "null java.awt.Button". Can anyone explain me the program's behavior?
Thanks & Regards
I "try", I "catch" and "finally" WIN !!!
Hi Swapna, you are calling test2 method by passing button1's value.Inside the test2 method, the button reference variable points to a new Button object created inside the method.But button1 reference variable inside the main method still points null. Similarly, you are calling test1 method by passing button2 's value.Inside the test1 method the button reference variable points to null, but still button2 variable in main method points to the created button object in the main. Understand that in test1 and test2 the button reference variables do not change the value of the object passed rather they point to a null and newly created object respectively. To understand it better try to print the hashcode values of the button reference variables. hope this helps.
remember, when you pass a Object reference, you are passing a COPY of the reference. So, if you change the value of the REFERENCE (not the Object of the reference) inside the method you'll be changing only the value of the reference inside the method. Got it? Let's see an example:
It will show:
For the Object, any reference with the same Object will have the same value for it. Now see two reference's that have like a "pointer" for the same object, but, when we call a method, one of them loose your reference for the Object.
Look this example and see if it will make the things clear: