Three kinds of variables, three rules¶
โ Java 17 ยท Giving Variables Their First Value ยท 1/3
Initializing means giving a first value¶
String title; // declared: no value yet
title = "Inception"; // initialized
String genre = "Sci-Fi"; // both at once
Whether Java fills in a value for you depends on where the variable is declared.
Where a variable lives decides the rule¶
| Kind | Declared | First value |
|---|---|---|
| Local variable | inside a method, constructor or block | none: you must assign it before reading it |
| Instance variable (field) | in the class, outside methods | automatic default, when the object is created |
Class variable (static field) |
in the class, with static |
automatic default, when the class is set up |
public class Movie {
static int totalMovies; // class variable: 0
int views; // instance variable: 0
public void play() {
int count; // local variable: no value
System.out.println(count); // โ doesn't compile
}
}
Java never guesses a value for a local variable. Reading one before assigning it is a compiler error.
The default values¶
Fields (instance and static) start with these values:
| Type | Default |
|---|---|
byte, short, int, long |
0 |
float, double |
0.0 |
boolean |
false |
char |
'\u0000' (the null character) |
any object type (String, Movieโฆ) |
null |
In a Movie class, that gives sensible starting points: no views yet (0), no rating yet (0.0), not available yet (false), no title yet (null).
null means "points to no object". Printing a null field shows the word null; calling a method on it throws a NullPointerException.
Fields versus locals, side by side¶
public class Movie {
String title; // โ null
double rating; // โ 0.0
public void displayInfo() {
String label = "Now Showing"; // local: assigned by you
System.out.println(label + ": " + title);
}
}
Class-level fields are initialized for you; method-level variables need your attention. One exception breaks the field rule: final fields.