Skip to content

Instantly share code, notes, and snippets.

@BT-ICD
Created May 5, 2021 14:10
Show Gist options
  • Save BT-ICD/4040e12ac85118d9e8a2946ffbc48349 to your computer and use it in GitHub Desktop.
Save BT-ICD/4040e12ac85118d9e8a2946ffbc48349 to your computer and use it in GitHub Desktop.
Example: Array variables contain references to arrays.
/**
* Example: Array variables contain references to arrays. When you make an assignment to an array variable, it simply copies the reference. But it doesn’t copy the array itself.
* To create a new copy of array java.util.Arrays provides a method named copyOf.
* Reference:
* https://books.trinket.io/thinkjava2/chapter7.html
*
* */
import java.util.Arrays;
public class ArraysByRefDemo {
public static void main(String[] args) {
int[] a = {10,20,30};
int [] b = a;
int[] c;
a[0]=501;
//print all the elements of A
System.out.println(Arrays.toString(a));
//print all the elements of B
System.out.println(Arrays.toString(b));
c = Arrays.copyOf(a,a.length);
a[0]=101;
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(c));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment