Default Values of Data Types
When a new bank account is opened, the balance starts at zero. Nobody types the zero in; it's the sensible starting value. Java does the same for some variables: if you don't give a field or an array element a value, Java fills in a default value. But for local variables inside a method, it deliberately refuses, and that difference trips up many beginners.
Who Gets a Default, and Who Doesn't
| Where the variable is | Default value? |
|---|---|
| Instance variable (field) | Yes |
| Static variable | Yes |
| Array element | Yes |
| Local variable (inside a method) | No: must be assigned before it's read |
The Default for Each Type
| Type | Default value |
|---|---|
byte, short, int | 0 |
long | 0L |
float | 0.0f |
double | 0.0 |
char | '\u0000' (the "null character", code 0) |
boolean | false |
Any reference type (String, arrays, objects) | null |
See the Defaults
public class Ticket {
int seat;
double fare;
boolean paid;
char coach;
String passenger;
public static void main(String[] args) {
Ticket t = new Ticket();
System.out.println("seat: " + t.seat);
System.out.println("fare: " + t.fare);
System.out.println("paid: " + t.paid);
System.out.println("coach code: " + (int) t.coach);
System.out.println("passenger: " + t.passenger);
int[] counts = new int[3];
System.out.println("counts: " + java.util.Arrays.toString(counts));
}
}seat: 0
fare: 0.0
paid: false
coach code: 0
passenger: null
counts: [0, 0, 0]How it works
- Lines 2 to 6 declare five fields without giving them values.
- Line 9 creates a
Ticketobject, and Java fills every field with its default. - Line 13 casts the
chartointto show its code, 0. Printed as a character,'\u0000'is invisible. - Line 16 creates an array of three
ints. Each element starts at0, andArrays.toStringon line 17 prints them all.
Try it yourself: add a field long pnr; and print it. Then make the array a String[] instead of int[]. What do the elements start as?
Why Locals Get No Default
Inside a method, Java insists that you assign a variable before reading it:
Errs6.java:4: error: variable x might not have been initialized
System.out.println(x);
^This is on purpose. A local variable that you forgot to set is almost always a bug. A silent 0 would hide it; a compile error points straight at it. Fields are different: an object may legitimately be created before all its fields are known, so Java gives them safe starting values.
Common Mistakes
Expecting a local int to start at 0. It doesn't compile. Write int total = 0;.
Comparing a default char with a space. '\u0000' is not ' '. The space character is code 32.
Assuming a new String[] contains empty strings. Its elements are null, not "".
Practice
- Easy: Write the default value for each: an
intfield, abooleanarray element, aStringfield, adoublestatic variable, a localint. - Harder: Create a
boolean[] seatsBooked = new boolean[5];, mark seats 1 and 3 as booked, and print all five values.
Key Takeaways
Was this tutorial helpful?