References, aliasing, null & == vs equals
Computer Science · AP CSA
Question 1 of 10
0What is printed by: int[] a = new int[3]; System.out.println(a == null);
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
References, aliasing, null & == vs equals explained
In Java, a variable that holds an object does not store the object itself. It stores a reference, which is a pointer to where the object lives in memory. Two variables can hold references to the same object, and this is called aliasing. A change made through one variable is then visible through the other, because both refer to the same object. Aliasing is useful, but it causes errors when a programmer expects a copy and gets a shared object instead.
The keyword null is a reference that points to no object at all. Fields that have not been given an object hold null by default, and calling a method on a null reference causes a NullPointerException. The double equals operator checks whether two references point to the same object. The equals method compares the contents of objects, but its behaviour depends on how the class defines it. Strings define equals to compare their characters.
Worked example
Consider this code, where an int array is an object.
- int[] a = {1, 2, 3}; creates one array and stores a reference to it in a.
- int[] b = a; copies the reference, not the array, so a and b now alias the same array.
- b[0] = 99; changes the shared array, so a[0] is now 99.
- a == b is true, because both refer to the same object.
Now create c = new int[]{99, 2, 3}. The contents match, but a == c is false, because they are two different objects.
What you will practise
75 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.
Example questions
- When the == operator is used with two object references, what does it compare?
- What does the equals method of the String class compare?
- What value does a reference variable hold when it has not been assigned an object?
- What happens when a method is called on a reference variable whose value is null?
- Which statement about String objects is correct?
- No other Box objects have been created. After Box b = a; where a already refers to a Box object, how many Box objects exist?
- Which expression tests whether a String variable s is null?
- What does the new keyword do in Java?
…and 67 more.