Bookmark Topic Watch 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
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
Java always makes a copy of the argument and passes the copy. The called method has a local copy of the data. If the method changes the data it changes the copy, so the original value is not changed.

When we pass a primitive like int this make perfect sense. The method gets its own int variable, a copy of the original.

When we pass an object we have to think very precisely. The value that is copied and sent along is a reference or pointer to the object. The method gets its own copy of the pointer, but it doesn't get its own copy of the object. If the method changes its copy of the pointer to point to a different object the original pointer is not affected. If the method changes some of the attributes of the object, it changes the original object.

In short: In Java, object references are passed by value and primitive types are passed by value.

(posted by Stan James in this thread)

Other Resources:

  • http://www.javaranch.com/campfire/StoryPassBy.jsp
  • relevant section of the Java Language Specification

  •  
    Consider Paul's rocket mass heater.
      Bookmark Topic Watch Topic
    • New Topic