Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Java autoboxing extend to method invocations of methods of the autoboxed types?

I want to convert a primitive to a string, and I tried:

myInt.toString(); 

This fails with the error:

int cannot be dereferenced 

Now, I get that primitives are not reference types (ie, not an Object) and so cannot have methods. However, Java 5 introduced autoboxing and unboxing (a la C#... which I never liked in C#, but that's beside the point). So with autoboxing, I would expect the above to convert myInt to an Integer and then call toString() on that.

Furthermore, I believe C# allows such a call, unless I remember incorrectly. Is this just an unfortunate shortcoming of Java's autoboxing/unboxing specification, or is there a good reason for this?

like image 234
Mike Stone Avatar asked Aug 07 '08 01:08

Mike Stone


People also ask

What does Autoboxing do in Java?

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

What is the difference between boxing and Autoboxing in Java?

Boxing is the mechanism (ie, from int to Integer ); autoboxing is the feature of the compiler by which it generates boxing code for you.

Who is responsible for performing Autoboxing and unboxing in Java?

Who is responsible for performing Autoboxing and unboxing in java? Java compiler is responsible for making such conversions. Before java 5 we used to write such code for performing Autoboxing.

When did Java add Autoboxing?

Autoboxing and unboxing are introduced in Java 1.5 to automatically convert the primitive type into boxed primitive( Object or Wrapper class).


1 Answers

Java autoboxing/unboxing doesn't go to the extent to allow you to dereference a primitive, so your compiler prevents it. Your compiler still knows myInt as a primitive. There's a paper about this issue at jcp.org.

Autoboxing is mainly useful during assignment or parameter passing -- allowing you to pass a primitive as an object (or vice versa), or assign a primitive to an object (or vice versa).

So unfortunately, you would have to do it like this: (kudos Patrick, I switched to your way)

Integer.toString(myInt); 
like image 162
Justin Standard Avatar answered Sep 24 '22 20:09

Justin Standard