In: Computer Science
How are primitive and reference types different an examples of how copying works differently for these two types.
Primitives vs. References
byte, short, int, long, float, double, boolean,
char
String, Scanner, Random, Die, int[], String[]
, or
any objects.Assignment
Example
This above statement copies the value stored in x(that is 10) to y.
The above statement assigns the array x to values {1,2,3,4,5} and then we copy y[] = x, this does not copy the entire array but y is given as a reference of the memory represented by x.
So in the next line when we assign y[2] = 7, it is also reflected in x as we are using the same memory for both the arrays. Generally programming languages comes with specific utilities if we need to copy the values in the array.
If we print x[] and y[] after the y[2]=7 statement, we will find both x and y are same.