N
N
nagvv2016-03-05 23:16:37
Java
nagvv, 2016-03-05 23:16:37

All the same, in java passes an array by reference or not?

Everywhere they write that java passes primitives by value, and objects by reference.
And they also write that an array is an object passed by reference.
So if it should be passed by reference then why do I have an array passed by value?

import java.util.Arrays;

public class ssulk 
{
  public static void main(String[] args)
  {
    int[][] a = new int[2][2];
    a[0][0]=1;
    a[0][1]=2;
    a[1][0]=3;
    a[1][1]=4;
    
    System.out.println("1  "+a[0][0]);
    
    a[0][0]=a[1][1];
    System.out.println("2  "+a[0][0]);
    put(a[0],a[1]);
    System.out.println("3  "+a[0][0]);
    
  }
  
  static void put(int[] a,int[] b)
  {
    System.out.println("4  "+a[0]);
    a=b;
    //a=Arrays.copyOf(b, 2);
    System.out.println("5  "+a[0]);
  }
}

here outputs
1 1
2 4
4 4
5 3
3 4
>> passes by value. so what's up?
new question on the answer:
1) so like Arrays.copyof() changes the value(!)(?) of the array, but displays the same
2) How to make it work as it should?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
one pavel, 2016-03-05
@nagvv

Everything worked correctly. An array is an object and is passed
by reference. But the reference is passed by value.
a=b;
here you are already manipulating copies of references inside the method.

A
abs0lut, 2016-03-06
@abs0lut

Everything in Java is pass-by-value . However, if you're passing a reference, it's the value of the reference.

source

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question