Java Reference
In-Depth Information
int age;
Person (){
}
}
You probably expect this to lead to a
null pointer exception
at line 12 now, because you never
initialized the name or age of the
Person
object referenced by
employee
. However, if you run this
code, the following line is output to the console:
null is 0 years old.
This is because Java will
automatically initialize fields of an object to a default value,
null
for objects and
0
for
int
, and it is
possible to print these values.
You might be wondering then, how a
null pointer exception
comes up, aside from actually ini-
tializing a variable to null. One way this can happen, shown in the following code, is when a second
object type
JobType
is added and a
Person
object is assigned a
JobType
object.
public class ExceptionExamples {
public static void main(String[] args) {
Person employee = new Person();
printPerson(employee);
}
public static void printPerson(Person myPerson){
System.out.println(myPerson.name + " is " + myPerson.age +
" years old and works as a " + myPerson.job.JobName);
}
}
class Person{
String name;
int age;
JobType job;
Person (){
}
}
class JobType{
String JobName;
int salaryBand;
JobType (){
}
}
Search WWH ::
Custom Search