• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Pass By Value Problem

 
Ranch Hand
Posts: 186
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
So it takes a day for light to pass through this glass? So this was yesterday's tiny ad?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic