I was wondering why primitives aren't nullable.
Today I read this
The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables. Ordinary value types cannot be null. However, C# 2.0 introduced nullable value types. See Nullable Types (C# Programming Guide).
So I know that there are nullable primitives like int?
in C# or Integer
in Java but why aren't int's or bool's etc. directly nullable ?
This question is not directed towards any programming language but are there differences in the programming languages why they don't allow primitives to be null ?
Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.
C# allows for the use of nullable types, where a primitive value type can be either one of its "normal" values or null .
Non-primitive types are created by the programmer and is not defined by Java (except for String ). Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot. A primitive type has always a value, while non-primitive types can be null .
And null is used only for objects because there memory size is not fixed. So by default we have, int a=0; and not. int a=null; Same with other primitive types and hence null is only used for objects and not for primitive types.
The null
value points to nothing, so it is a (non-existent) reference. In Java, Object
is a reference type, therefore object-type values can hold null values (eg. Integer
). Primitives on the other hand are value types and not reference types, therefore they cannot be null
.
Java has been designed this way because of performance considerations. Working with references are slower and more memory consuming than working with values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With