Null and Default Types in Java
Java has a really simple and predictably way of handling null and default types. Each variable that extends from
java.lang.Object may become null and is null on default. All other variable types like int, boolean, float and char have specific values assigned to them on default, if you don’t initialize them by yourself. For example, boolean’s are always
false on default:
|Data Type||Default Value (for fields)|
|String (or any object)||null|
These are the default values for primitive data types in Java, according to Oracle. For you as a programmer / coder this means that you don’t necessarily need to initialize these values on default, but most of the times it’s a code convention and better to do than not.
undefined on default, so it hasn’t been initialized yet. On the other side,
null means that you assigned something to that variable, so it is non-empty or currently not existing/available.
str = 'some string';
str = null;
console.log(str == null); // true
console.log(str == undefined); // true!
console.log(str === undefined); // false!
str declared and not initialized, so it is
undefined by default. Line 5 makes the variable to a string and 9 to
null equals (
undefined, because it is ‘minified’ to
undefined. This is without type checking. If you also check for type equality, you would use the last line (
===considers the type. So
'42' !== 42
==does not consider the type. So
'42' == 42