0

I've seen many posts about call by value and reference, but can barely find solutions for reference data types such as int[ ], or char[ ]. For example:

char b[] = new char[2];
b[0] = 'h';
b[1] = 'i';
char c[] = new char[2];

c = b;     //   copy by reference?
copy(c,b); //   copy by value?

b[0] = 'b';
b[1] = 'y';

System.out.print(b[0]);
System.out.println(b[1]);

System.out.print(c[0]);
System.out.println(c[1]);     

public static void copy(char[] dst, char[] src) {
dst[0] = src[0];
dst[1] = src[1];
}

c = b; changes value because c gets b's address?

copy(c,b); can't change value because it is copy by value? But I thought char[ ] is one of reference data types which can change the value. For example int[ ] is reference data type so it can change the value like below:

int[] d = new int[1];
d[0] = 1;        
function(d);
System.out.println(d[0]); 

public static void function(int[] a) {
    a[0] = 4;
}  

Does anyone know about this?

andy shon
  • 17
  • 7
  • Remove `c=b;` (which destroys the other array) before `copy(c,b)`. In Java, everything that isn't a primitive is a descendant of `Object`. That includes arrays, `String`(s) and the wrapper types. – Elliott Frisch Dec 23 '15 at 03:32
  • @ElliottFrisch I'm not asking that question. one of them can be commented out – andy shon Dec 23 '15 at 03:34
  • 1
    Arrays are objects, and any object-valued variable is of 'reference datatype'. Arrays are not special cases. – user207421 Dec 23 '15 at 04:05

2 Answers2

0

In Java:

method arguments are indeed passed-by-value, but all object and array variables in Java are reference variables.

Java passes all primitive data types by value. This means that a copy is made, so that it cannot be modified. When passing Java objects, you're passing an object reference, which makes it possible to modify the object's member variables. If you want to pass a primitive data type by reference, you need to wrap it in an object.The easiest of all is to pass it as an array . Your array only needs to contain a some element, but wrapping it in an array means it can be changed by a function.

Zia
  • 1,080
  • 10
  • 23
-1

As pointed out by @Tom and @EJP in the comments, references to objects are passed by value.

When you do c = b, you are setting c to reference the same object as b. When you do something to either, it shows up in the other.

However, your copy method is taking a reference to the objects c and b by value. This means that if you do something to either object, that change shows up when the function returns. This includes setting an element of an array. However, when you do dest[0] = src[0], you are copying a primitive char. No references are being passed, and if you change one array afterwards, the other array isn't affected. They are still two separate arrays that now happen to have the same contents.

James Westman
  • 2,468
  • 1
  • 14
  • 19