-2

Integer.valueOf takes in String and int as arguments but when I pass Character, it doesn't require casting and compiler doesn't enforce anything.

Character doesn't extend String class, it just implements Serializable and Comparable

Character charc = '1';
System.out.println(Integer.valueOf(charc));
System.out.println(Integer.valueOf(charc.toString()));

output:

49
1

Isn't it kind of design flaw or I am thinking in the wrong direction? Please write the reason in comments when you down-vote it.

enter image description here

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78

2 Answers2

5

This is specifically covered by JLS 5.2, Assignment conversion. (Passing a parameter to a method is essentially like assigning a value to a variable.)

Assignment contexts allow the use of one of the following:

...

  • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.

What's happening here is that the Character is being unboxed to char; and then the char is being widened to int.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
2

The char ist auto-widened to an int, which is a perfectly valid parameter for Integer.valueOf()

Java converts some types automatically if the required type contains all of the current type like char to int or int to long. See the Java Language Specification for details.

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
Nicktar
  • 5,548
  • 1
  • 28
  • 43