Tip: Java Instance initialization is critical
One of my previous blogs, I showed how the instances are initiated in the Java, if you wish see the Java Constructor Loading Tips. In this blog, I will give an example, where developer can confused. For example, the following code compiles but throws the NPE in the runtime.
package com.ojitha.green; /** * @author Ojitha * */ public class Child { //singleton public static final Child GIRL = new Child(); private Child() {} private static final Boolean GENDER = true; private Boolean gender = GENDER; public Boolean isMale(){ return gender;} public static void main(String... args){ String gender = Child.GIRL.isMale() ? "Female":"Male"; System.out.println(gender); } }
In the line 17, you get the exception. At the time of creating GIRL, initializing the object variable is happen after the constructor is called. At the time of the GIRL singleton instance is created, Boolean type gender variable is already initialized to null, that cause to the NPE.
Suppose you have change the Boolean to primitive type boolean as shown in the following list, Then the output is “Female”.
package com.ojitha.green; /** * @author Ojitha * */ public class Child { //singleton public static final Child GIRL = new Child(); private Child() {} private static final boolean GENDER = true; private boolean gender = GENDER; public boolean isMale(){ return this.gender;} public static void main(String... args){ String gender = Child.GIRL.isMale() ? "Female":"male"; System.out.println(gender); } }
See the difference use of boolean and its wrapper class behaviour.
Comments
Post a Comment
commented your blog