What are initialized by Java object fields?

Is this nullfor type Object?

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

Will it salways be null?

What about simple types like int? What will it be? Zero or arbitrary value?

What about local variables in methods?

public void meth() {
    int i;
}

What is uniform value i?


However, relying on such defaults is considered a bad programming style.

Well, what are you suggesting 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?

+9
source share
6 answers

From the Suns Java Tutorial

, . , . , , . , , .

.

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 

; . , , . .

+28

-: String null. 0 ( 0.0 ).

: .

: String s = ""; s = ""; . , . ( , , - null.)

+4

: null; ints, longs shorts to 0; null; boolean - false. .

, , , .

+3

0/false. null. , , ...

+2

setter: , , . .

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

Google Collections/Google Guava:

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

, , :

/**
 * 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 this case, you should always specify the correct range of values ​​for your properties in the JavaDoc installer and / or class.

+1
source

JLS 4.12.5. Initial Variable Values

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

0
source

Source: https://habr.com/ru/post/1725816/


All Articles