3

I'm editing this question to differentiate it from this one, and to remove the dreaded "why?"

If I have a java method that returns the java object Integer, the java compiler allow me to assign that to a primitive int. This seems to be asking for runtime trouble. ie. what if Integer is null?

public class SomeClass {
    private Integer someIntegerObject;

    public Integer getSomeIntegerObject() {
        return this.someIntegerObject;
    }
}

SomeClass someClass = new SomeClass();
//much later...
int someIntegerPrimative = someClass.someIntegerObject();

This will blow up at runtime if someIntegerObject was set to null at all, but it seems like something that could easily be caught at compile time.

This functionality is called "unboxing" and its opposite is "auto-boxing". It is intended to save the developer time and readability from unboxing each of these manually.

The question is: what are the best strategies for catching potential issues here at compile-time?

Daniel Patrick
  • 3,530
  • 4
  • 26
  • 46

2 Answers2

6

The JRE / Compiler does something called Auto Unboxing - which is designed to save developer time when it comes to activities like this.

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.

https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

Edit: you might want to read this re your point on null objects - looks like a runtime error NullPointerException will be thrown, but you can setup most IDE's to warn about auto unboxing at compile time to help you either:

a) Make sure you have the right exception handling or;

b) Make sure you are not relying on the behaviour at all (always calling the method to get the primitive value)

Community
  • 1
  • 1
IaMaCuP
  • 825
  • 5
  • 19
  • I've edited the question to remove the "why?" and put the focus on compile-time solutions. Since your answer offers those, I will choose this as the solution. – Daniel Patrick May 20 '16 at 18:03
3

The concept your talking about is Auto-unboxing. The value of a type wrapper (here Integer) is automatically extracted whenever it is needed. Basically auto-unboxing removes the tedium of manually boxing and unboxing values. It is mostly important to Generics, which operate only on objects. This feature makes working with Collections Framework much easier. And we can always catch a NullPointerException. Java provides pretty good exceptional handling mechanism. Let's use it even if tiniest possibility of exceptions exist.

Jay Patel
  • 500
  • 1
  • 3
  • 14