Revisiting Primitive-Type Field Initialization


Only reference-type fieldsfields that can point to objects in memorycan be initialized to null or have a value of null. You cannot initialize a variable of the primitive type to null, nor can such a variable ever have a value of null.

This includes boolean variables and variables of the numeric type (char and int, plus the rest that you'll learn about in Lesson 10: byte, short, long, float, and double). Fields of the boolean type have an initial value of false. Each of the numeric types has an initial value of 0.

Even though 0 is often a useful initial value for a numeric type, you should explicitly initialize the field to 0 if that represents a meaningful value for the field. For example, explicitly initialize a field to 0 if it represents a counter that will track values starting at 0 when the Java VM instantiates the object. If you are going to explicitly assign a more meaningful value to the field in later execution of the code, then you need not explicitly initialize the field to 0.

Provide explicit initializations only when necessary. This will help clarify what you, the developer of the code, intend.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net