Hii guys....

i am a new programmer of java. i want to implement a problem using CALL BY REFERENCE as i have done in C. please help me to do this.

Recommended Answers

All 2 Replies

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.