I have just started learning groovy and I am reading "Groovy in Action". In this book I came across a statement that it doesn’t matter whether you declare or cast a variable to be of type int or Integer.Groovy uses the reference type ( Integer ) either way.
So I tried to assign null value to a variable with type int
int a = null
But it is giving me below exception
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'null' with class 'null' to class 'int'. Try 'java.lang.Integer' instead at Script1.run(Script1.groovy:2)
Then I tried to assign null value to a variable with type Integer
Integer a = null
and it is working just fine.
Can anyone help me understand how groovy
behaves such way or the reason behind it?
The core problem is that primitives can’t be null. Groovy fakes that out with autoboxing.
If you store a null
value in a number, you can’t store that in a int/long/etc
field. It’s not correct to convert a null number
to 0, since this might be valid values. Null
means that no value or choice has been made yet.
int
is a primitive type
and it is not considered as an object
. Only objects
can have a null
value while int
value can't be null
because It's a value type rather than a reference type
For primitive types
, we have fixed memory size i.e for int
we have 4 bytes
and null
is used only for objects
because there memory size is not fixed.
So by default we can use :-
int a = 0
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