Java Reference
In-Depth Information
"Bart Baesens",
"Aimee Backiel",
"Seppe vanden Broucke"
};
book2 = new Book(); // Set second book
book2.title = "Catcher in the Rye";
book2.authors = new String[]{"J. D. Salinger"};
Every instance variable you define defaults to a particular value, depending on the variable type. For
instance, you might wonder what happens if you ask for the title of a book, without specifying a title first:
Book book3 = new Book();
// Oops, forgot to set title...
System.out.println("Title equals: "+book3.title);
The answer is that “Title equals: null”. For variables with a class type, the default value is a special
keyword representing emptiness,
null
. Since
String
is a non‐primitive class, its default value is thus
null
. Remember, as discussed in Chapter 2, the default values, per data type, are:
➤
For
boolean
:
false
➤
For
byte
:
0
➤
For
short
:
0
➤
For
int
:
0
➤
For
long
:
0L
➤
For
float
:
0.0f
➤
For
double
:
0.0d
➤
For
char
:
\u0000
(the null character)
➤
For
String
or any object:
null
Note that these default values apply only to fields (instance variables). That means if you try to be
clever and add the following to the code snippet:
Book book;
System.out.println("Now, book equals: "+book);
book = new Book();
System.out.println("And now, book equals: "+book);
Eclipse will complain about the
book
variable not being initialized. This can be fixed like so:
Book book = null;
System.out.println("Now, book equals: "+book);
book = new Book();
System.out.println("And now, book equals: "+book);
The same applies for other variables you define that are not instance variables:
int a = 0;
System.out.println("int a equals"+a);
Search WWH ::
Custom Search