Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java does not allow null while declaring primitive data types [duplicate]

Tags:

This is in continuation to my previous question and accroding to answers of this question Declaration of wrapper classes

Java wraps primitive data type to wrapper classes then why

char c = null; // invalid
int i = null; // invalid

is not allowed but

Character cObj = null; // valid
Integer iObj = null; // valid

is allowed.

like image 209
Vishrant Avatar asked Oct 22 '13 07:10

Vishrant


People also ask

Can primitive data types be null in Java?

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 primitive double be null?

Primitives (int, double, float, etc) are by definition not reference types, so they cannot have null values.

Is null a primitive data type?

Summary. JavaScript has the primitive types: number , string , boolean , null , undefined , symbol and bigint and a complex type: object .

Why primitive data types are not allowed in Java generics?

Answer is Object is superclass of all objects and can represent any user defined object. Since all primitives doesn't inherit from "Object" so we can't use it as a generic type.


1 Answers

Because primitives represent value and Object variables represent references (something like pointers) to complex data objects. There is no null value general, it is a special keyword that "references to nothing" or empty reference - this is highly unprofessional answer, but I guess it will be most appropriate.

Besides, what could be in your opinion, numerical value of null? 0? -1? But, those are valid integers so what else?

I strongly suggest that you start familiarizing yourself with the following complex java tutorial. Every aspect that you have been asking about is explained there and supported with examples.

like image 121
Antoniossss Avatar answered Dec 29 '22 01:12

Antoniossss