I have the following Java 8 code (simplified for demonstration):
public Double fooBar(int a) {
return Double.valueOf(a);
}
Now IntelliJ IDEA tells me that I have unnecessary boxing in the return statement. I'd understand this problem if a
were a double
type, but for an int
I feel that I need the boxing to have the conversion to double
.
Is there a good way to refactor this code which I currently don't see or is the error message from IntelliJ IDEA at this point simply not optimal?
Thanks for help
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The technique lets us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.
In the java. lang package java provides a separate class for each of the primitive data type namely Byte, Character, Double, Integer, Float, Long, Short. Converting primitive datatype to object is called boxing.
If you use alt-enter to use the suggested resolution"Remove boxing", the result is this:
public Double fooBar(int a) {
return (double) a;
}
In this case the conversion from int
to double
is very explicit, whilst at the same time avoiding manual boxing.
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