EugeneP
EugeneP

Reputation: 12003

What are java object fields initialized with?

Is it null for Object type?

class C {
    int i;
    String s;
    public C() {}
}

Will s be always null?

What about simple types as int? What will that be? Zero or an arbitrary value?

What about local variables in methods?

public void meth() {
    int i;
}

What is the unitialized value of i?


Relying on such default values, however, is generally considered bad programming style.

Ok, what do you suggest we do?

class A {
    String s = "";
    int i = 0;
}

OR:

class A {
    String s;
    int i;
    public A() {
        // default constructor
        s = "";
        i = 0;
    }
}

Which is better and why?

Upvotes: 12

Views: 27251

Answers (6)

Roland
Roland

Reputation: 7875

JLS 4.12.5. Initial Values of Variables

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):

For type byte, the default value is zero, that is, the value of (byte)0.

For type short, the default value is zero, that is, the value of (short)0.

For type int, the default value is zero, that is, 0.

For type long, the default value is zero, that is, 0L.

For type float, the default value is positive zero, that is, 0.0f.

For type double, the default value is positive zero, that is, 0.0d.

For type char, the default value is the null character, that is, '\u0000'.

For type boolean, the default value is false.

For all reference types (§4.3), the default value is null.

Upvotes: 0

michiel
michiel

Reputation: 6276

From suns java tutorial

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.

The following chart summarizes the default values for the above data types.

Data Type   Default Value (for fields)
byte                    0 
short                   0   
int                     0 
long                    0L 
float                   0.0f 
double                  0.0d 
char                    '\u0000' 
boolean                 false
String (or any object)  null 

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

Upvotes: 33

nd.
nd.

Reputation: 8942

As for the setter-method question: The whole point of setters is that they can check if the object passed conforms to the requirements of the class. e.g.

public void setS(String s) {
  if (s == null)
     throw new IllegalArgumentException("S must not be null");
  this.s = s;
}

Or, with Google Collections/Google Guava:

public void setS(String s) {
  this.s = Preconditions.checkNotNull(s, "S must not be null");
}

Of course, you can define arbitrary constraints, e.g.:

/**
 * Sets the foo. Legal foo strings must have a length of exactly 3 characters.
 */
public void setFoo(String foo) {
  if (foo == null)
     throw new IllegalArgumentException("Foo must not be null");
  if (foo.length() != 3)
     throw new IllegalArgumentException("Foo must have exactly 3 characters");
  ...

Of course in such a case you should always state the correct range of values for your properties in the JavaDoc of the setter and/or of the class.

Upvotes: 1

Ash
Ash

Reputation: 9446

For member variables: The default value for String is null. The default value for primitives is 0 (or 0.0 for floating point values).

For local variables: You must explicitly initialise a local variable before using it.

As to the second part of your question: You can always say String s = ""; in the member variable definition, or s = ""; in the constructor. Then you know it will have a non-null value. (Also, in your setter you'd need to ensure that someone doesn't try and set it back to null.)

Upvotes: 4

Joel
Joel

Reputation: 30156

Fields: Objects default to null; ints, longs and shorts to 0; Strings to null; booleans to false. It's all here.

The compiler will force you to initialise variables declared in methods, local variables, yourself.

Upvotes: 3

Bozho
Bozho

Reputation: 597324

Primitive fields are initialized to 0 / false. Objects are initialized to null . But frankly, you could have tried that one..

Upvotes: 2

Related Questions