Sub topic 5
References, Default Values, and Element Types
A Java array is an object that holds a fixed number of values. Each value is called an element. An index is the position of an element, starting at 0.
An array can hold primitive values or references to objects. This difference affects what an element contains and what happens when variables share an array.
A primitive type is a basic kind of value, such as int or boolean. An object is a value created from a class. A class describes what data an object can hold and what actions it can perform.
A reference is a value that identifies an object. You can think of it as a way to reach that object. The reference is not the object itself.
An array variable holds a reference
Even an array of primitive values is an object. A variable such as int[] first holds a reference to that array object.
When you assign one array variable to another, both variables refer to the same array. The assignment does not make a new array.
Try this complete program. Save it as Main.java.
public class Main {
public static void main(String[] args) {
int[] first = {10, 20};
int[] second = first;
second[0] = 99;
System.out.println(first[0]);
second = new int[] {7, 8};
second[0] = 42;
System.out.println(first[0]);
System.out.println(second[0]);
}
}Compile and run it with:
javac Main.java
java MainThe output is:
99
99
42At first, first and second refer to the same array. Changing second[0] therefore changes the element that first[0] reaches.
Later, second = new int[] {7, 8} makes second refer to a different array. It does not change first. The two variables now lead to different arrays.
For the other Java programs in this chapter, replace the contents of Main.java, then compile and run it in the same way.
Element types
The type before the brackets tells Java what kind of element an array holds.
| Array type | What each element holds |
|---|---|
| `int[]` | An `int` value, such as `12` |
| `boolean[]` | A `boolean` value: `true` or `false` |
| `double[]` | A `double` value, such as `2.5` |
| `String[]` | A reference to a `String` object, or `null` |
A String is an object that represents text. The type String[] is an array type; String is its element type.
Java checks that a value can be assigned to the element type. For example, you cannot put a String into an int[]. Some assignments use a conversion: an int value can be assigned to a double element.
For a primitive array, the elements hold primitive values. For a reference array, the elements hold references. The objects reached by those references are separate from the array.
Default values in a new array
When you create an array with a size, Java gives every element a default value. A default value is the value Java supplies before you assign another one.
int[] scores = new int[3];All three elements of scores start at 0.
| Element type | Default value |
|---|---|
| `byte`, `short`, `int`, or `long` | Zero |
| `float` or `double` | `0.0` |
| `char` | The zero character, U+0000 |
| `boolean` | `false` |
| A reference type, such as `String` | `null` |
A char holds a character value. Its default is not a space or the digit 0.
null is a special value meaning that a reference does not refer to an object. A new String[] contains null references; Java does not create a String object for each element.
An initializer is a set of values supplied when an array is created. For example, in int[] scores = {8, 9}, the elements have the supplied values 8 and 9.
See the defaults
This program creates arrays without supplying element values:
public class Main {
public static void main(String[] args) {
int[] numbers = new int[1];
double[] prices = new double[1];
boolean[] flags = new boolean[1];
char[] letters = new char[1];
String[] words = new String[1];
System.out.println(numbers[0]);
System.out.println(prices[0]);
System.out.println(flags[0]);
System.out.println((int) letters[0]);
System.out.println(words[0]);
}
}The output is:
0
0.0
false
0
nullThe expression (int) letters[0] converts the character value to an integer for display. This makes its zero value visible.
A primitive element cannot hold null. For example, an element of int[] always holds an int value, even when that value is the default zero.
Checking for null
Trying to use null as though it referred to an object causes a NullPointerException. This is an error that occurs while the program is running.
For example, a String has a length() method. A method is a named action that code can call. You can call length() on a String object, but not on a null reference.
public class Main {
public static void main(String[] args) {
String[] words = new String[1];
if (words[0] == null) {
System.out.println("No word yet");
}
words[0] = "Ada";
if (words[0] != null) {
System.out.println(words[0].length());
}
}
}The output is:
No word yet
3The first check uses == null to ask whether the element refers to no object. The second uses != null to ask whether it does refer to an object.
A missing array and an empty array are different:
- A variable set to
nullrefers to no array. - A variable that refers to
new String[0]refers to an array with zero elements.
You can read the length of the empty array, and it is 0. You cannot read the length of a null array reference.
Local variables and default values
An array’s elements receive defaults, but a local variable does not become usable in the same way. A local variable is declared inside a method.
Java’s compiler checks that a local variable has been assigned before you read it. The compiler is the tool that turns Java source code into a form Java can run. For example, declaring int[] items inside a method does not let you use items until you assign it a value.
A field is a variable belonging to an object or a class. Fields receive defaults too: an int[] field starts as null unless given another value. That is different from an existing int[] array, whose elements start at zero.
Sharing objects through array elements
A reference array can have several elements that refer to the same object. Changing that object through one element is then visible through the other.
The next program defines a Box class. Each Box has an int field named value.
class Box {
int value;
}
public class Main {
public static void main(String[] args) {
Box shared = new Box();
shared.value = 5;
Box[] boxes = {shared, shared, new Box()};
boxes[0].value = 9;
System.out.println(boxes[1].value);
boxes[0] = new Box();
boxes[0].value = 4;
System.out.println(boxes[0].value);
System.out.println(boxes[1].value);
}
}The output is:
9
4
9Here is what happens:
sharedrefers to oneBoxobject.- Both
boxes[0]andboxes[1]receive a reference to that same object. - Changing
boxes[0].valuechanges the shared object, soboxes[1].valueis also9. - Assigning a new
Boxtoboxes[0]changes that element’s reference. It does not changeboxes[1].
The third element also refers to a new Box. Its value field starts at zero because Java gives fields default values.
Not every object allows its contents to change. A String is immutable, meaning its text cannot be changed after the String is created. You can still assign a different String reference to an element of a String[].
Check your understanding
Exercise
If a and b refer to the same int[], what does b[0] = 6 do to a[0]?
Show answer
It makes a[0] equal to 6, because both variables refer to the same array.
Exercise
What does each element of new String[2] contain? Are there two empty String objects?
Show answer
Each element contains null. No String objects are created for those elements.
Exercise
Two elements of a Box array refer to the same Box. What happens if you assign a new Box to the first element?
Show answer
Only the first element's reference changes. The second element still refers to the original Box.