I'm studying a simple example of Builder Design Pattern.
So my question is, if I try to instantiate my Phone class directly, it wont accept null for the int parameter which is understandable since it is a primitive type.
However when I use the builder and I don't set the value of an Int variable(which will remain null) the director somehow changes its value to 0.
Phone p=new PhoneBuilder().setOs("Android").setRam(2).getPhone();
p.Processor == null
at this point. so in getPhone()
when the phone constructor is called, the value of processor
is supposed to be null
I tried to watch the variable with the debugger but I can't find nor understand why it changes from null
to 0
.
public class Phone {
private String os;
private int ram;
private String processor;
private double screenSize;
private int battery;
public Phone(String os, int ram, String processor, double screenSize, int battery) {
super();
this.os = os;
this.ram = ram;
this.processor = processor;
this.screenSize = screenSize;
this.battery = battery;
}
}
and here is my builder:
public class PhoneBuilder {
private String os;
private int ram;
private String processor;
private double screenSize;
private int battery;
public PhoneBuilder setOs(String os) {
this.os = os;
return this;
}
public PhoneBuilder setRam(int ram) {
this.ram = ram;
return this;
//...
public Phone getPhone() {
return new Phone(os, ram, processor, screenSize, battery);
}
}
This has nothing to do with any design pattern. Nulls are not possible for primitives, only for objects. An int
, not to be confused with an Integer
, cannot be null
. It was never null
.
So when you say this:
However when I use the builder and I don't set the value of an Int variable(which will remain null)
You've made an incorrect assumption. It wasn't null
and won't remain null
.
Here's a simple example:
public class NoNullForPrimitives{
private static int myInt;
public static void main(String[] args){
System.out.println(myInt); //prints 0
}
}
For more details, see the Default Values section under https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html