Search code examples
javareferencepass-by-reference

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.


Solution

  • 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.