What is pass by value in java and how is it different for strings, int and array data types?

Viewed 21
public class Main {
    public static void.  main(String[] args) {
        int a = 10;
        changeInt(a);
        //This prints 10
        System.out.println(a);
    }
    
    static void changeInt(int num){     
        num += 5;
    }
}

Above in the code, why does the changeInt() method not change the value of the argument passed to it. Though the same thing works for arrays (as in the following code).

public class Main {
    public static void main(String[] args) {
        int [ ] myarr = {10,20,30};
        changeArr(myarr);
        //This prints 5 instead of 10
        for (int i= 0; i< 3; i++){          
            System.out.println(myarr[i]);
        }
    }
    
    static void changeArr(int [ ] arr){     
        arr[0] = 5;
    }
}

Please explain the reason in as simple words as possible.

0 Answers
Related