my dog learned polymorphism
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

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Pass By Value Problem" Watch "Pass By Value Problem" New topic

Pass By Value Problem

Vijay Chandran
Ranch Hand

Joined: Jan 07, 2007
Posts: 186

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.

Rob Spoor

Joined: Oct 27, 2005
Posts: 20136

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.

How To Ask Questions How To Answer Questions
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24193

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:
subject: Pass By Value Problem
It's not a secret anymore!