Sitemap
✨ Srinivas Vadige

✨ Srinivas Vadige

Full Stack Developer (Java, Js) linkedin.com/in/SrinivasVadige

Press enter or click to view image in full size

Java Default Primitive and Reference Variable Values

2 min readOct 27, 2024

--

int i = 0;
char c = '\0' or '\u0000';
double d = 0.0;
boolean bool = false;
Integer wrapperClass = null;
String str = null;
MyClass classVar = null;

We know that we cannot assign null to a primitive type like int, but we can assign it to non-primitives like String and Integer. Additionally, we cannot print int i or Integer i without assigning a value to them first, as this will result in a java.lang.Error compile error.

Get ✨ Srinivas Vadige’s stories in your inbox

Join Medium for free to get updates from this writer.

Similarly int[] and Integer[] arrays are different

boolean[] boolArr = new boolean[3];
System.out.println(Arrays.toString(boolArr )); // [false, false, false]

Boolean[] boolArr2 = new Boolean[3];
System.out.println(Arrays.toString(boolArr2)); // [null, null, null]

int[] intArr= new int[3];
System.out.println(Arrays.toString(intArr)); // [0, 0, 0]

Integer[] intArr2 = new Integer[3];
System.out.println(Arrays.toString(intArr2)); // [null, null, null]

Now let’s deep dive into the above theory using a class

public class BinaryTreeNode {
public Integer size;
public int val;
public BinaryTreeNode left, right;
public BinaryTreeNode() {}
public BinaryTreeNode(int val) { this.val = val; }
public BinaryTreeNode(int val, BinaryTreeNode left, BinaryTreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}

Now initialize this BinaryTreeNode class

int i; // local or non-class variable
BinaryTreeNode node = new BinaryTreeNode();
System.out.println(node.val); // 0
System.out.println(node.size); // null
System.out.println(node.left); // null
System.out.println(node.right); // null
System.out.println(i); // java.lang.Error: Unresolved compilation. The local variable i may not have been initialized

If we don’t explicitly initialize the values for class variables immediately after invoking the class, these reference variables will automatically be set to null, and the primitives will default to their respective initial values. This behavior can be observed in the first code block

--

--