Created
May 5, 2021 14:10
-
-
Save BT-ICD/4040e12ac85118d9e8a2946ffbc48349 to your computer and use it in GitHub Desktop.
Example: Array variables contain references to arrays.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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