3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by JamesCherrill
0

It is simple, in java by default all calls on primitives are : call be copy.
And for non-primitives its call be reference.
Example:

void foo()
{
     Object a = new Object();
     foo2(a);
}
void foo2(Object b)
{
      //So here, be definition b will point to the same Object as to what a did.
}

I hope it helps

0

Sorry purijatin but that's not right, although it is a common mistake.
All calls in Java are calls by value. There is no such thing as a call by reference in Java.

@hackit: I have no idea what kind of problem you have in mind, but all calls in Java are calls by value. There is no equivalent to C's call by reference. People sometimes get confused about this because some values in Java are primitives (int, boolean etc) and others are references (all objects, arrays etc). In both cases the call is by value (ie a copy).
So, to explain purijatin's example more fully:
void foo()

{
     Object a = new Object();
     foo2(a);
}
void foo2(Object b)
{
      //So here, be definition b will point to the same Object as to what a did.
}

a is a reference variable that can hold a reference to any Object. It's initial value is null. new Object() creates an Object and returns a reference to it. That reference is then assigned to a. When foo2(a); is executed a new reference variable is created for the parameter (referred to as b in the method), and the value of a is copied into b. The parameter b is not, and cannot be, a reference to the argument a; it is a copy of its value.

To quote the Java Language Reference section 8.4.1 Formal Parameters

When the method or constructor is invoked (ยง15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared Type, before execution of the body of the method or constructor.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.