Mathur
Mathur

Reputation: 71

Implicit conversion in wrapper class

I have confusion in Number Wrapper Class in Java.

These two assignments look symmetric - a char is assigned to Integer, and an int is assigned to Character. However, the first assignment

Integer i = 'a';

gives Compilation Error, while the second assignment

Character ch2 = 97;

is allowed. Why?

Upvotes: 0

Views: 927

Answers (4)

GhostCat
GhostCat

Reputation: 140457

The rules for boxing conversions can be found in the Java Language Spec, chapter 5.1.7

Boxing conversion converts expressions of primitive type to corresponding expressions of reference type. Specifically, the following nine conversions are called the boxing conversions:

... followed by a list of valid conversions from primitive types to reference types.

The point is: in any case, a conversion must take place.

If you had

int a = '97'

that is fine; as that is a widening conversion (sectin 5.12 in the JLS). But that case

Integer i = '97' 

isn't listed as "valid" conversion for Auto-boxing. In other words: the JLS doesn't allow for it; and this the compiler doesn't do it either. ...

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

Although int i = 'a' works fine, converting the same to Integer is not allowed, because it requires a boxing conversion.

Java's boxing conversion is defined only for eight cases:

  • From type boolean to type Boolean
  • From type byte to type Byte
  • From type short to type Short
  • From type char to type Character
  • From type int to type Integer
  • From type long to type Long
  • From type float to type Float
  • From type double to type Double

Since 'a' is a char literal, Java does not allow conversion from char to Integer: a character literal is always of type char.

However, when you write

Character ch2 = 97;

Java compiler sees that 97 is in the valid range for char (i.e. 0..65535), so it treats 97 as char, not int, and allows the boxing conversion. Trying the same with an out-of-range constant produces an error:

Character ch3 = 65536; // error: incompatible types: int cannot be converted to Character

Upvotes: 5

clubberLeng
clubberLeng

Reputation: 1

This is because when setting a character to an integer it's returning the ASCII code number which is a primitive int.

Upvotes: 0

Aaron Brock
Aaron Brock

Reputation: 4536

Integer i = 'a' just wraps int i ='a'. Since 'a' is not an int it throws an error.

Likewise, Character ch2 = 97 wraps char ch2 = 97. However, 97 is an valid char! It represents the character "a". Example:

System.out.println((char) 97); //Output: a

Upvotes: 0

Related Questions