0

I have the following test class in a file named Sandbox.java:

package cas;

public final class Sandbox {

    public static void main(String[] args) {
        int primitive = 42;
        Integer boxed = primitive;
    }

}

This is something I would expect to work because of autoboxing. However, it failed to compile with the error: "Type mismatch: cannot convert from int to Integer". To isolate the test case, I put the file in a different Eclipse project, where the code is exactly identical except that package cas; is replaced with package sandbox. In this project, it compiled normally.

I am using compiler compliance level 1.8, with what I believe is the most up to date JDK. Since autoboxing was introduced in 1.5 if I recall correctly, there shouldn't be any issues with int –> Integer conversion, or so I thought.

I checked the Properties for both projects, and every page with the "Enable project specific settings" checkbox has it disabled. So there should be no difference between the two projects' compilation, no?

I don't understand why this code would ever give an error in a Java 1.8 environment.

Resigned June 2023
  • 4,638
  • 3
  • 38
  • 49

1 Answers1

0

It turned out that package cas declared a type cas.Integer. Since names declared in the local package shadow implicitly imported system types, cas.Integer was used in the declaration implicitly instead of java.lang.Integer, and the error message did not give a fully qualified type name.

This problem can be resolved by declaring the variable java.lang.Integer boxed = primitive or (my personal favorite) adding import java.lang.Integer, because specifically imported types shadow implicitly imported package types (which respectively shadow implicitly imported system types). Or by not declaring a class named Integer. (Although in this case there was a good reason.)

This was, of course, a silly error, but it might be enlightening to someone (seeing as how the error message seemed impossible).

Resigned June 2023
  • 4,638
  • 3
  • 38
  • 49
  • 2
    Personally I don't think this question will be very helpful, partly because those who encounter this type of mistake will 90% of the time not bother making another project. – Jeroen Vannevel Nov 11 '14 at 17:04
  • You could have figured this out if using `java.lang.Integer`. – Luiggi Mendoza Nov 11 '14 at 17:09
  • 1
    @JeroenVannevel Well, if the consensus is that this question will not be very helpful, then it can certainly be deleted. I, for one, have been programming for years and I found the sequence of shadowing for implicit imports quite interesting. But clearly I cannot speak for everyone else. – Resigned June 2023 Nov 11 '14 at 17:54