Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass object by reference in Java [duplicate]

Tags:

java

Possible Duplicate:
How to pass by reference in Java

Is it possible to pass object by reference in Java

Like in C#

public static void SomeMethod(ref Object obj)
{
...
}
like image 909
NDeveloper Avatar asked May 18 '11 12:05

NDeveloper


People also ask

Does passing by reference make a copy?

pass-by-reference does not make any copy, it gets the reference of the object itself by just renaming it, so no any copying operation.

Can you pass object by reference in Java?

No, that is not possible in Java. In Java, all arguments to methods are passed by value. Note that variables of non-primitive type, which are references to objects, are also passed by value: in that case, a reference is passed by value. Note that passing a reference by value is not the same as passing by reference.

How do you duplicate an object in Java?

The clone() method of the class java. lang. Object accepts an object as a parameter, creates and returns a copy of it.

What happens when an object is passed by reference in Java?

Object references are passed by value The reason is that Java object variables are simply references that point to real objects in the memory heap. Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.


2 Answers

All variables of objects are references to the object. When you pass an object to a method, you are passing the reference of the object already. If you don't want the original object to be affected, you must clone it first.

like image 146
Explosion Pills Avatar answered Oct 12 '22 22:10

Explosion Pills


No, that is not possible in Java.

In Java, all arguments to methods are passed by value. Note that variables of non-primitive type, which are references to objects, are also passed by value: in that case, a reference is passed by value. Note that passing a reference by value is not the same as passing by reference.

like image 22
Jesper Avatar answered Oct 12 '22 22:10

Jesper