Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why aren't primitives nullable

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 ?

like image 976
Bongo Avatar asked Oct 14 '15 09:10

Bongo


People also ask

Can a primitive 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.

Can primitives be null C#?

C# allows for the use of nullable types, where a primitive value type can be either one of its "normal" values or null .

Can non-primitive data types be 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 .

What does primitive data type null mean?

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.


1 Answers

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.

like image 94
erosb Avatar answered Sep 27 '22 00:09

erosb