This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

pass by value  RSS feed

 
sai donthneni
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am confused about pass by value and pass by refernce in java as some texts uses pass-by-refernce when objects refernces are passed to the methods and some texts say that pass-by-refernce does not exist in java and it is just the pass by value that exists and the same is used by the object refernce.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your problem in understanding may be because Java is so simple: people look for complexity and then are confused when they don't find it. Java uses pass-by-value. End of story. The implication of this is:

1. When primitive values, like int values, are passed, a copy of the value is passed. Attemting to alter the copy doesn't alter the original variable:

2. When object references are passed, a copy of the reference is passed. Attempting to alter the local object variable by assigning to it changes the value of the local variable, but not the original reference variable. On the other hand, the underlying object (if the reference is non-null) is not copied, and the original reference and the method parameter start off refering to this same object

C++, because of parameter types like X& is more complicated. Look there for call-by-reference semantics!
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All parameter passing in Java is by value. When the parameter type is a primitive, then the value of the actual parameter is copied into the formal parameter. When the parameter type is a non-primitive, the formal parameter becomes a copy of the actual reference. This means that within a method, you can make changes to the original object referred to by the actual reference by using the formal parameter unless you point the formal parameter to another object.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As the people above already said, Java = pass by value. Always.

When you pass a reference, the reference is passed by value. Note that this is something different than pass by reference.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!