Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use references in Java?

I want to use reference in Java but I don't know how! for example in C++ we write:

void sum(int& x)
{
    ...
}

but in Java & sign is a compiler error! please help me to understand references in Java.

like image 614
Mahdi_Nine Avatar asked Jan 17 '11 11:01

Mahdi_Nine


People also ask

What is reference in Java programming?

A reference is an address that indicates where an object's variables and methods are stored. You aren't actually using objects when you assign an object to a variable or pass an object to a method as an argument. You aren't even using copies of the objects. Instead, you're using references to those objects.

Is there reference in Java?

How about objects or references? In Java, all primitives like int, char, etc are similar to C/C++, but all non-primitives (or objects of any class) are always references.

What is the use of reference object in Java?

A reference also contains information to assist in creating an instance of the object to which the reference refers. It contains the Java class name of that object, as well as the class name and location of the object factory to be used to create the object.


1 Answers

Objects are passed by reference by default Objects are accessed by reference, but there is no way to create a reference to a primitive value (byte, short,int, long). You either have to create an object to wrap the integer or use a single element array.

public void sum(int[] i){
   i[0] = ...;
}

or

public void sum(MyInt i){
   i.value = ...;
}
public class MyInt{
   public int value; 
}

for your example something like the following could work

public int sum(int v){
   return ...;
}

or

public int sum(){
   return ...;
}

Update:

Additional/Better description of object references:

Java Objects are always accessed by a reference. Like the primitive types this reference is passed by value (e.g. copied). Since everything a programmer can access in java is passed by copying it (references, primitives) and there is no way to create a reference to a primitive type, any modification to a method parameter (references, primitives) only affects the local copy within the method. Objects can be modified within a method since both copies of the reference (local and other) still point to the same object instance.

example:

Modify a primitive within method, this only affects the internal copy of i and not the passed value.

void primitive(int i){
  i = 0;
}

Modify a reference within method, this only affects the internal copy of ref and not the passed value.

 void reference(Object ref){
    ref = new Object();//points to new Object() only within this method
 }

Modify an object, visible globally

void object(List l){
   l.add(new Object());//modifies the object instead of the reference
}

Both the array and MyInt above are based on the modification of an object.

like image 191
josefx Avatar answered Oct 04 '22 17:10

josefx