initialization redundancy

gudii9
gudii9 used Ask the Experts™
on
Avoid Redundant Initialization (0-false-null)
It’s very unnecessary to initialize member variables to the following values: 0, false and null. Because these values are the default initialization values of member variables in Java. For example, the following initialization in declaration is unnecessary:
1
2
3
4
5
public class Person {
    private String name = null;
    private int age = 0;
    private boolean isGenius = false;
}
This is also redundant:
1
2
3
4
5
6
7
8
9
10
11
public class Person {
    private String name;
    private int age;
    private boolean;
 
    public Person() {
        String name = null;
        int age = 0;
        boolean isGenius = false;
    }
}
Therefore, if you know the default initialization values of member variables, you will avoid unnecessary explicit initialization. See more here:

Open in new window


i am not clear on below

This is also redundant:


does it mean initialization in the constructor as well apart from at class level

public Person() {
        String name = null;
        int age = 0;
        boolean isGenius = false;
    }
}

https://www.codejava.net/coding/10-java-core-best-practices-every-java-programmer-should-know
Please advise
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Senior Director of Technologyy
Commented:
When you first initialize an object, the constructor is called.  

public Person() {
        String name = null;
        int age = 0;
        boolean isGenius = false;
}

Open in new window


The reason that this is redundant is that when you declared your variables, you set them to the same values.  

private String name = null;
    private int age = 0;
    private boolean isGenius = false;

Open in new window


So essentially when you instantiate an object, it is initializing the variables as they are declared, and then resetting them to a new value in the constructor (which are the exact same values).

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial