References, null and initialization
What you will learn
A reference variable holds a reference to an object or the special null reference. Java distinguishes primitive values from references. Local variables must be definitely assigned before use; fields and array components have default values.
public class Main { public static void main(String[] args) { String title = null; System.out.println(title == null); title = "Atlas"; System.out.println(title == null); }}Expected output:
truefalseThe first reference denotes no object; the later reference denotes a string.
How it works
A String variable can hold a reference to text. String title = null; is an explicit null assignment, not an empty string. Comparing a reference with null checks whether it denotes an object. In a class, an int field defaults to 0 and a reference field defaults to null; local variables do not get those implicit defaults. Field syntax is previewed here only to show the distinction.
public class Main { public static void main(String[] args) { String label = ""; System.out.println(label == null); }}Expected output:
falseAn empty string is still a string object.
Common mistakes
Do not read an uninitialized local such as int count; System.out.println(count);. The compiler rejects the read. Do not invoke methods on a null reference; this can throw NullPointerException.
Try it yourself
Create a String reference initially null, assign it a book title, and predict both null comparisons.
These are local Java practice tasks, not automatically graded ByteMind exercises. Use a patched JDK; no network or third-party dependency is needed.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
References, null and initialization — knowledge check
Check your understanding of references, null and initialization.
Does an uninitialized local int automatically contain 0?
Is an empty string equal to null using ==?