Looking at the constructor you have wrote and according to what is called the "variables scope", the instance of "a" which you are passing to the methods "getB" and "getC" is NOT the class instance member, but it is the reference of variable "a" passed in input to the constructor, thus the class instance member "b" will be already initialized when the method "getC" is invoked.
Surely, if you pass a null value to the constructor (i.e. new Constructor(null);
) you will always get a "NullPointerException", but if the variable "a" is NOT null, you will have eventually:
- Instance class member "a" = reference of input variable "a"
- Instance class member "b" = string returned by
"a.trim()
, where leading and trailing space will be cut.
- Instance class member "c" = concatenation of "a" and "b"
Here is an example of what I said:
public class Constructor {
private final String a;
private final String b;
private final String c;
public Constructor(String a) {
this.a = a;
this.b = getB(a);
this.c = getC(a, b);
}
public String getB(String a) {
return a.trim();
}
public String getC(String a, String b) {
return a + b;
}
public static void main(String[] args) {
Constructor myConstructor = new Constructor(" Hello ");
System.out.println(myConstructor.a);
System.out.println(myConstructor.b);
System.out.println(myConstructor.c);
new Constructor(null);
}
}
The result will be:
Hello
Hello
Hello Hello
Exception in thread "main" java.lang.NullPointerException
at Constructor.getB(Constructor.java:15)
at Constructor.(Constructor.java:10)
at Constructor.main(Constructor.java:27)