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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven
  • 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

  •  
    I knew I would regret that burrito. But this tiny ad has never caused regrets:
    Gift giving made easy with the permaculture playing cards
    https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
      Bookmark Topic Watch Topic
    • New Topic