954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Help me.

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.

hackit
Newbie Poster
18 posts since Sep 2011
Reputation Points: 10
Solved Threads: 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

purijatin
Light Poster
41 posts since Jun 2009
Reputation Points: 10
Solved Threads: 5
 

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.

JamesCherrill
Posting Genius
Moderator
6,371 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: