Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unnecessary unboxing in java - how to refactor the code?

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

like image 730
Mathias Bader Avatar asked Feb 21 '17 08:02

Mathias Bader


People also ask

What is the difference between Autoboxing and unboxing in Java?

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.

Why do we need boxing and unboxing Java?

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.

What is boxing in Java?

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.


1 Answers

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.

like image 129
vikingsteve Avatar answered Sep 21 '22 05:09

vikingsteve