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:
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 classclass my_number {// public member variablepublic int number;// default constructorpublic my_number(){number = 1;}}// driver functionclass Main{public static void main (String [] arguments){// creating objectmy_number object = new my_number();// printing before updateSystem.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++;}}
This is a simple method in which changes are returned by the function to update the original memory address.
// driver functionclass 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 functionpublic static int update( int number ){// increments number.number++;return number;}}
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 numbernumber[0]++;}}
Free Resources