Groovy vs Java - Autoboxing

 By default Groovy have autoboxing feature because of its dynamic nature. By default Groovy treats all the primitive types as objects, for example Integer for int, Float for float etc. See the below example.
int integerVariable = 10;
println integerVariable.class.name

float floatVariable = 0.5f
println floatVariable.class.name

char charVariable = 'c'
println charVariable.class.name

double doubleVariable = 1.5d
println doubleVariable.class.name

boolean boolVariable = true
println boolVariable.class.name

 Here I have created the some variable for primitive types and print the corresponding class name. This result would be,
java.lang.Integer
java.lang.Float
java.lang.Character
java.lang.Double
java.lang.Boolean
  In Java, auto boxing and unboxing involve constant casting. But Groovy automatically treats all the primitive types variable as Object. That's why the print statement prints the corresponding class name for primitive types.

Comments

Popular Posts