pass by value for array in java

I have a code as follows

public static int mat(final int a[]) {
    for(int i=0;i<a.length;i++)
        a[i]=a[i]+10;
    System.out.println("Mat Function");
    for(int i=0;i<a.length;i++)
        System.out.println(a[i]);
    return 1;
}

public static void main(String[] args) {
    int arr[]={1,2,3,4,5,6};

    mat(arr);
    System.out.println("Main");
    for(int i=0;i<arr.length;i++)
        System.out.println(arr[i]);
}

My main must show values 1,2,3,4,5,6 and mat function must show 11,12,13,14,15,16. But both are showing 11,12,13,14,15,16. How to rectify this and pass array by value to the function.

Jon Skeet
people
quotationmark

You never pass an array object at all. You pass an array reference, which is always going to be passed by value.

If you want to create a copy of the array, then pass a reference to that copy to the method, the simplest approach is probably to call clone:

mat(arr.clone());

Note that calling clone() on an array always makes a shallow clone - irrelevant here, but if you had a Person[] for example, it wouldn't create a copy of each Person referred to by the original array... so changes to the cloned array (e.g. clonedArray[0] = new Person()) wouldn't be seen by the calling code, but changes to the objects referred to by the array (e.g. clonedArray[1].setName("Fred")) would be seen via the original array, because the two arrays would refer to the same objects.

As a side note, I'd strongly recommend keeping the type information in one place for variables, e.g. int[] arr rather than int arr[]. I'd also recommend using braces for if, for, and while statements even when the body is only a single statement.

people

See more on this question at Stackoverflow