Why does this Java code generate an error in one Eclipse project but not the other?

795 views Asked by At

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.

1

There are 1 answers

3
Resigned June 2023 On BEST ANSWER

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).