aspose file tools*
The moose likes Beginning Java and the fly likes Pass By Value Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Pass By Value Problem" Watch "Pass By Value Problem" New topic
Author

Pass By Value Problem

Vijay Chandran
Ranch Hand

Joined: Jan 07, 2007
Posts: 178


Dear Friends,

When i execute this code, the output is 1 0 1.
Java uses pass-by-value. How come the values of a and c change but not the value of b?

Kindly provide your help.

Regards,
Vijay.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19693
    
  20

Because in method g it updates the value of the parameter, not the field of the object. This is called shadowing.

Array c is also shadowed, but because that's a reference to an object, the parameter points to the same object, so the same object is modified.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24184
    
  34

There are two different variables named "b". One is a member variable, while the other is a parameter to the "g()" method. The parameter is changed, but the member is printed.

The value of "c" is not changed; only the contents of the array c is changed. When you pass an array, it is a reference to the array is passed by value. "Pass by value" for objects like arrays doesn't mean that the value of the array or object itself is copied; only the reference is copied.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Pass By Value Problem