How to pass by reference in Java

One of the biggest confusions in Java is whether it is pass by value or pass by reference.

Java is always a pass by value; but, there are a few ways to achieve pass by reference:

  1. Making a public member variable in a class
  2. Return a value and update it
  3. Create a single element array
svg viewer

Ways to create a pass by reference


1. Making a public member variable in a class:

In this method, an object of a class passes in the function and updates the public member variable of that object; ​changes are visible in the original memory address.

// my class
class my_number {
// public member variable
public int number;
// default constructor
public my_number()
{
number = 1;
}
}
// driver function
class Main{
public static void main (String [] arguments)
{
// creating object
my_number object = new my_number();
// printing before update
System.out.println("number = " + object.number);
// update function called.
update(object);
//printing after update.
System.out.println("number = " + object.number);
}
// update function.
public static void update( my_number obj ){
// increments number variable.
obj.number++;
}
}

2. Return a value and update it:

This is a simple method in which changes are returned by the function to​ update the original memory address.

// driver function
class Main{
public static void main (String [] arguments)
{
int number = 1;
// printing before update.
System.out.println("number = " + number);
// update function returns a value.
number = update(number);
// printing after update.
System.out.println("number = " + number);
}
// update function
public static int update( int number ){
// increments number.
number++;
return number;
}
}

3. Create a single element array:

In this, a single element array is created and passed as a parameter to the function; the effect is visible in the original memory address.

// driver function.
class Main{
public static void main (String [] arguments)
{
// single element array.
int number[] = { 1 };
// printing before update.
System.out.println("number = " + number[0]);
//update function.
update(number);
// printing after update.
System.out.println("number = " + number[0]);
}
// update function.
public static void update( int number[] ){
// increments the number
number[0]++;
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved