The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confusion about program output!!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Confusion about program output!!!" Watch "Confusion about program output!!!" New topic

Confusion about program output!!!

Vijay Tidake
Ranch Hand

Joined: Nov 04, 2008
Posts: 146

Hi Guys,

I came across the following code snippet.

The output of program is
15 0

Now my confusion is,

At Line 3 v is pointing to the object having Hascode Value@123ab
and after that(at Line 5) the v is pointing to the new object having Hascode Value@456cd
and hense the output at Line 6 is 15 0

So my question is that why ouptput is not
15 0
As we are assining the new object to the reference at Line 5 after returnig from second()
the value reference must points to the object created at Line 4(Hashcode Value@456cd) and not to the object created at Line 1( Hascode Value@123ab)

The important thing is not to stop questioning.Curiosity has its own reason for existing.
Torsten Oppermann
Ranch Hand

Joined: Dec 22, 2010
Posts: 62

in Line 3 you set the value of v.i to 20. Then you use the reference value to point to a completely different object, created in Line 4 with the value of int i = 15
When reassigning v in the method second, the reference variable v in method first is unaffected since its method local.

Key word : Pass by Value ! not by Reference

what i mean is: the Value (an Object in this case) is passed to the second method, so changes affect the actual object. However after the reassigning to the new Object this isnt the case anymore

Hope i could help

OCPJP 6 - 93%
Vijay Tidake
Ranch Hand

Joined: Nov 04, 2008
Posts: 146

Ok Thanks

Got the point...
I agree. Here's the link:
subject: Confusion about program output!!!
jQuery in Action, 3rd edition