0

Possible Duplicate:
Is Java pass by reference?

Hi guys,

I have a question about the arguments passing in Java, I read it from a book "In Java the arguments are always passed by value", what does this mean?

I have no experience of C++ and C, so it is a little bit hard for me to understand it. Can anyone explain me?

Community
  • 1
  • 1
  • @glowcoder: the body of the question actually asks for an explanation of what "pass by reference" means, so it's not really an exact duplicate – Michael Borgwardt Apr 23 '11 at 09:32
  • @Michael that may be the case. It's not exactly relevant though. The body of the question isn't *directly* part of the criteria for closing a question. It's only implicitly part of the criteria. "This question covers exactly the same ground as earlier questions on this topic; its answers may be merged with another identical question." For those of use who do know the realm of Java, we recognize that questions for "pass by reference" and "pass by value" certainly "cover the same ground" and the answers certainly qualify for merging. – corsiKa Apr 23 '11 at 09:38

3 Answers3

2

Yes, java method parameters are always passed by value. That means the method gets a copy of the parameter (a copy of the reference in case of reference types), so if the method changes the parameter values, the changes are not visible outside the method.

There are two alternative parameter passing modes:

Pass by reference - the method can basically use the variable just like its caller, and if it assigns a new value of the variable, the caller will see this new value after the method finishes.

Pass by name - the parameter is actually only evaluated when it's accessed inside the method, which has a number of far-reaching consequences.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
0

It means that when you pass a variable to a method, the thing that is passed is the value that is currently held by the variable. Thus, subsequents assignments to the method's argument will not affect the value of that variable (caller side), nor the opposite.

A pass-by-reference means that the callee receives a handle to the caller-side variable. Thus, assignments within the method will affect the caller-side variable.

Itay Maman
  • 30,277
  • 10
  • 88
  • 118
0

In Java everything is an object. Object is a pointer like C. But in Java, it points the memory place of a class. Passed by value means, what object's value is, this value is passed by value. For example; Integer a=new Integer(); Integer b=new Integer(); setAInteger(b); public void setAInteger(Integer c){ a= c; } After this operation a points the memory place of b. Lets say, at the beginning a=2500 b=3500, after method is called, new a value is 3500. By the way, 2500 and 3500 are memory addresses.

olyanren
  • 1,448
  • 4
  • 24
  • 42