Integer l = Integer.valueOf("100"); // valid no compilation
Integer l = "100"; //Error : cannot convert from string to integer
Why I am facing the above error please suggest to me. (Need to use Autoboxing concept for second line)
Integer l = Integer.valueOf("100"); // valid no compilation
Integer l = "100"; //Error : cannot convert from string to integer
Why I am facing the above error please suggest to me. (Need to use Autoboxing concept for second line)
Any value in quotes in java is treated as a String
, and strings are objects, Auto-boxing is not supported in JAVA
for Objects, So If you need then you have to do explicitly.
auto-boxing is only allowed from primitives to it's wapper classes.
The following table lists the primitive types and their corresponding wrapper classes, which are used by the Java compiler for auto-boxing and unboxing:
Primitive type Wrapper class
boolean Boolean
byte Byte
char Character
float Float
int Integer
long Long
short Short
double Double
You can read more about this here.
Firstly, this is not called an Autoboxing but is an ordinary static method call with a String
as a parameter. The simplest examples of autoboxing are:
Integer i = 1;
Character ch = 'a';
Your snippet tries to instantiate a String
as an Integer
which are in the Java world incompatible types. Autoboxing happens only for the primitive data types.
Integer l = "100"; // Cannot convert from String to Integer
Integer l = 100; // Autoboxing happens
From JLS, ยง5.1.7:
Boxing conversion converts expressions of primitive type to corresponding expressions of reference type. [...]
"100"
in Java is of type String
. String
is not a primitive and therefore boxing does not apply.