File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pass By Value Problem

 
Vijay Chandran
Ranch Hand
Posts: 186
Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Pie
Posts: 20396
47
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic