Video lecture
Watch on YouTube(opens in a new tab)Sub topic 10
Default Values and Definite Assignment
When you create a variable, it needs a value before your program can use that value. In Java, some variables get a value automatically. Others must be given a value by your code.
A default value is a value Java supplies automatically. Definite assignment is the compiler’s check that a variable has been assigned before its value is read. The compiler is the tool that checks your Java code and turns it into a form the computer can run.
This chapter focuses on where defaults apply and how to make sure a local variable is ready to use.
Local variables need an assigned value
A local variable is a variable declared inside a method or a block of code. A method is a named set of instructions. A block is a group of statements between braces, { and }.
Java does not give local variables default values. You can declare a local variable without a value, but you must assign one before reading it.
For example, int score; declares a local variable. A later statement such as score = 10; assigns its value. Only then can a statement such as System.out.println(score); read it.
If you try to print score before assigning it, the compiler reports an error. The program cannot run until you fix the error.
Fields get default values
A class is a definition used to create objects. An object is a piece of data created from a class. A field is a variable declared in a class, outside its methods.
An instance field belongs to an object. A class field, marked with static, belongs to the class and is shared rather than belonging to one particular object.
Java gives both kinds of fields default values. If your code does not give a field another value, it keeps its default.
| Field type | Default value |
|---|---|
| `byte`, `short`, `int` | `0` |
| `long` | `0L` |
| `float` | `0.0f` |
| `double` | `0.0d` |
| `char` | The character with value zero, written as `'\0'` |
| `boolean` | `false` |
| Reference types, such as `String` | `null` |
A reference is a value that can point to an object. The value null means the reference does not point to an object. For example, a String field defaults to null, not to an empty string.
The default char is usually not visible when printed. It is not the character '0', which is the visible digit zero.
Try the defaults
Save this program in a file named DefaultValues.java:
class DefaultValues {
int count;
double price;
char marker;
boolean ready;
String label;
static int total;
public static void main(String[] args) {
DefaultValues example = new DefaultValues();
System.out.println("count: " + example.count);
System.out.println("price: " + example.price);
System.out.println("marker is zero: " + (example.marker == '\0'));
System.out.println("ready: " + example.ready);
System.out.println("label: " + example.label);
System.out.println("total: " + DefaultValues.total);
}
}Run these commands in the folder containing the file:
javac DefaultValues.java
java DefaultValuesThe new keyword creates an object. That object has its own count, price, marker, ready, and label fields. The program reads those fields using example.
The total field is a class field, so the program reads it using the class name. The program prints:
count: 0price: 0.0marker is zero: trueready: falselabel: nulltotal: 0
The == operator compares two values. The marker line checks whether the default char is '\0'.
Printing a null reference displays the word null here. But null is not a usable String object. Trying to call a method on it causes a NullPointerException, an error that happens while the program is running.
Array elements get default values
An array is a fixed-size group of values of the same type. When you create an array without listing its elements, Java gives each element the default for its type.
For example, new int[3] creates three elements, each with the value 0. Likewise, a new boolean array has false elements, and a new String array has null elements.
The array’s elements and the variable that refers to the array are different things. If the array variable is local, you must still assign it before reading it. The declaration int[] numbers; alone does not create an array or give the local variable a default value. Assigning new int[3] to numbers creates the array and makes it available through that variable.
Method parameters already have values
A parameter is a variable that receives a value when a method is called. A method call is a request to run that method.
For example, a method with the parameter int amount receives an integer from its caller. The method can read amount immediately because the call supplies its value. Parameters do not need local-variable defaults.
Definite assignment checks paths
A condition is a test that produces true or false. An if statement uses a condition to choose whether to run a block. An else block runs when that condition is false.
The compiler checks whether a local variable has a value on every path that could reach a read. A path is a possible sequence of statements through the code.
Save this program as BranchAssignment.java:
class BranchAssignment {
public static void main(String[] args) {
boolean isMember = true;
int discount;
if (isMember) {
discount = 5;
} else {
discount = 0;
}
System.out.println(discount);
}
}Compile and run it:
javac BranchAssignment.java
java BranchAssignmentThe program prints 5. If you change isMember to false, it prints 0.
The important point is that both paths assign discount before the print statement:
- When
isMemberistrue,discountbecomes5. - When
isMemberisfalse,discountbecomes0.
Now imagine removing the entire else block. The compiler would reject the print statement because the if block might not assign discount. The compiler does not assume that isMember will always be true just because that is its starting value here.
One way to fix the missing else is to assign a starting value when declaring discount. The if block can then change that value when needed. Another fix is to keep the else block, as in the program above.
Watch out for loops
A loop repeats a block of code. Some loops may run their block zero times. For example, a while loop skips its block if its condition is false at the start.
Suppose you declare a local variable and assign it only inside such a loop. After the loop, the compiler may reject a read of that variable: the assignment might never have happened.
A common fix is to assign a suitable starting value before the loop. That way, the variable has a value even if the loop does not run. Choose that value based on what the program should mean, rather than using zero just to silence an error.
A quick check before reading a variable
When you encounter a variable, ask:
- Is it a field? If so, Java gives it a default before any value your code assigns.
- Is it an array element created without a listed value? If so, it starts with the default for its element type.
- Is it a method parameter? If so, the method call supplies its value.
- Is it a local variable? If so, check that every path leading to the read assigns it first.
Exercise
A class has an int field named count. A method in that class also declares a local int named total without assigning it. Which variable can be read immediately?
Show answer
The field count can be read; its default is 0. The local variable total must be assigned before it is read.
Exercise
In the BranchAssignment program, what happens if you remove the else block and then try to compile? How can you fix it?
Show answer
Compilation fails because discount might not be assigned when the if condition is false. Restore the else block, or give discount a suitable starting value before the if.
Exercise
You create a new String array with two elements but do not list their values. What is in each element? Is either element an empty string?
Show answer
Each element is null. Neither is an empty string; each reference points to no object.