Sub topic 2
References, Default Values, and Element Types
An array is a fixed-size group of values called elements. A reference is a value that points to an object, such as an array. Two variables can refer to the same array. A change through either variable affects that array.
An array’s element type tells Java what each element can hold. A primitive is a basic value such as int or boolean. An array can also hold references to objects, such as strings.
When you create an array with new, Java gives each element a default value:
- Number types start at zero.
booleanstarts atfalse.charstarts at the character with code zero.- References start at
null, meaning they refer to no object.
Multidimensional and Jagged Arrays
An array can contain references to other arrays. You can think of these inner arrays as rows. A jagged array has rows of different lengths. For example, {{1, 2}, {3}} has one row with two elements and another with one.
Passing and Returning Arrays
A method is a named block of code. A parameter is a variable that receives a value passed to a method.
When you pass an array to a method, Java copies the reference, not the array. The method can use that reference to change the same array. Assigning a different array to the parameter does not change the caller’s variable. A method can also return an array reference.
Copying Arrays and Understanding Shallow Copies
Calling clone() creates a new array with the same elements. For an int[], the copy has its own number slots.
The copy is shallow: if the elements are references, the original and copy still refer to the same objects. For an array of arrays, the rows remain shared.
Worked example
Save this as Main.java. Run javac Main.java, then java Main.
public class Main {
static void change(int[] values) {
values[0] = 9;
values = new int[] {7};
}
static int[][] makeRows() {
return new int[][] {{1, 2}, {3}};
}
public static void main(String[] args) {
int[] values = new int[2];
System.out.println(values[0]);
int[] alias = values;
alias[0] = 4;
System.out.println(values[0]);
change(values);
System.out.println(values[0]);
int[][] rows = makeRows();
int[][] copy = rows.clone();
copy[0][0] = 8;
System.out.println(rows[0][0]);
}
}The output is 0, 4, 9, and 8, each on its own line. The final value is 8 because rows and copy share their first row.
Exercise
After the example runs, what happens to rows[1][0] if you set copy[1][0] to 6?
Show answer
It becomes 6. The outer arrays are separate, but they share the second row.