Rahul Tripathi
Rahul Tripathi

Reputation: 555

When pass any array in method and manipulate the array within method, why my actual array is manipulated

Here is a code with method fun(int[] a3), when call this function and pass a1[] and write manipulation code in method, actual a1[] value become {3,7,5} instead of {3,4,5}, We know Java is based on passbyvalue concept. Please suggest anyone.

public class test {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a1 = { 3, 4, 5 };
        int[] a2 = fun(a1);
        System.out.print(a1[0] + a1[1] + a1[2] + "");
        System.out.print(a2[0] + a2[1] + a2[2]);

    }

    static int[] fun(int[] a3) {

        a3[1] = 7;

        return a3;
    }
}

Output- 15 15

Upvotes: 0

Views: 58

Answers (3)

vikrant singh
vikrant singh

Reputation: 2111

In general, Java has primitive types (int, bool, char, double, etc) that are passed directly by value. Then Java has objects (everything that derives from java.lang.Object). Objects are actually always handled through a reference (a reference being a pointer that you can't touch). That means that in effect, objects are passed by reference, as the references are normally not interesting. It does however mean that you cannot change which object is pointed to as the reference itself is passed by value.

So you are passing copy of reference of you array a1[] into a3[] therfore both are pointing to same object into the memory.

enter image description here

Upvotes: 1

Michael Schneider
Michael Schneider

Reputation: 506

You can simply use

a2 = a1.slice();

its actually cloning the array, which removes the reference mentioned on @Eran's post.

Upvotes: 0

Eran
Eran

Reputation: 393781

Java passes a reference to the array by value. The array itself is a mutable object, and as such, can be modified within the method. You can't however, change the parameter passed to that method to refer to a different array. If you do, when you return from the method, the variable would still refer to the original array.

Upvotes: 1

Related Questions