DEV Community

C K Sanjay Babu
C K Sanjay Babu

Posted on • Originally published at blog.sanjaybabu.dev on

Day 7- Is Java pass by value or reference?

Again Java passes variables in functions similar to js. Check out the detailed explanations here.

Pass by Value

All primitive data types are passed by value in java.

class passByValue {
    public static void main(String args[]) {
        Integer i=0;
        increment(i);
        System.out.println("Value of i outside the function: "+i);
    }
    static void increment(Integer i){
        i++;
        System.out.println("Value of i inside the function: "+i); 
    }
}

/*
Output : 
Value of i inside the function: 1
Value of i outside the function: 0
*/

Enter fullscreen mode Exit fullscreen mode

Pass by Reference

Objects & arrays are pass by reference in java

class PassByValue {
  public static void main(String[] args) {
    Integer[] array = new Integer[2];
    array[0]=2;
    array[1]=3;
    add(array);
    System.out.println("Result from main: " +(array[0]+ array[1]));
  }

  private static void add(Integer[] array){
    array[0] = 10;
    System.out.println("Result from method: " +(array[0]+ array[1]));
  }
}

/*
Output:
Result from method: 13
Result from main: 13

*/

Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
cicirello profile image
Vincent A. Cicirello • Edited

Both cases are pass by value in Java. Parameters are always passed by value in Java. In the case of an object such as your array example, the value that is passed happens to be a reference to the object. If Java was pass by reference then if you put a statement like array = new Integer[5]; inside your add method in your example you'd observe the effect in the caller. But you don't see the effect of such a statement externally because of pass by value. It is a subtle distinction but Java is only pass by value. Inside the method you can change the state of the object parameter, but you can't change the object.

Collapse
 
sanjaybabu profile image
C K Sanjay Babu

Hey Vincent!
As you mentioned Objects and Array seem to follow pass by reference when glanced. Hence assumed it so. But, Yes. Java always passes by value indeed.

Thanks for clearing it up with a detailed explanation.
Will update the same in the blog shortly!
Cheers!