Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoboxing can't convert an int to an Integer

Tags:

java

I am a complete beginner and I'm trying to learn java. I read about the concept of Autoboxing and Unboxing here.

I am working on java version 1.8.0_05 and using Eclipse.

The code is :

class Test {
    public static void main(String[] args) {
        Integer iob = 100; // shows error -> Type mismatch: Cannot convert from int to Integer
    }
}

Thanks for the help.

like image 989
Dangling Cruze Avatar asked Jul 05 '14 23:07

Dangling Cruze


People also ask

Can int be converted to Integer?

Convert Int to Integer Using the Integer. valueOf() Method in Java. This is another that we can use to convert an int to an Integer in Java. Here, we used valueOf() method of the Integer class.

Can we assign int to Integer in Java?

In java one canâTMt assign a string value (containing an integer only) to an int variable directly or even by casting. In case of Integer we can assign string to an object of Integer type using the Integer(String) constructor or by even use parseInt(String) to convert a String literal to an int value.


2 Answers

You need to have your language level set to at least 1.5/5.0 to take advantage of autoboxing/unboxing.

Change your settings in Project --> Properties --> Java Compiler, chances are, it's not set to the right level.

Note this is NOT directly tied to the version of the JDK you're using, it simply means the level in which your java code will be interpreted as if it were no higher than the language level version, using any particular version of the JDK that is at least at or higher than the given language level setting.

IE: you're using JDK 1.8+, setting your language level to 5.0 means you will only be able to use java features that are up to JDK 1.5.

like image 85
Ryan J Avatar answered Sep 19 '22 09:09

Ryan J


Sounds like you have the wrong language level set in Eclipse.

See @Override gives error in eclipse? :

to change the language level go To Project > Properties > Java Compiler and set the language level there. You may need to click to enable project specific settings.

like image 39
Chris Martin Avatar answered Sep 19 '22 09:09

Chris Martin