Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between int and Integer type in groovy

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?

like image 600
Abhinandan Satpute Avatar asked Sep 09 '16 11:09

Abhinandan Satpute


1 Answers

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
like image 79
Saurabh Gaur Avatar answered Oct 23 '22 09:10

Saurabh Gaur