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

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • 4
    Autoboxing only works for primitives. `String` is not a primitive. I recommend reading a tutorial on the topic of autoboxing, e.g. [this one by Oracle](https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html). โ€“ Turing85 Feb 01 '20 at 14:59

3 Answers3

3

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.

Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42
2

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 
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
2

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.

Turing85
  • 18,217
  • 7
  • 33
  • 58