Day 7- Is Java pass by value or reference?

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
*/

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

*/