7

Why doesn't the following code compile

int n = 5;
char c = n;

but the following does compile

char c = 5;

Aren't I just assigning an integer value to char in both cases?

  • 3
    But this works, `char c = (char) 5;` Note that the range of int is much greater than that of char, and so assigning an int to a char is not guaranteed to be legit. – Hovercraft Full Of Eels Oct 19 '14 at 01:58
  • Oh, that makes sense. So it only comes down to the discrepancy between char- and int ranges? – Kermit the Hermit Oct 19 '14 at 02:00
  • 2
    My guess would be that char is a 16bit but int is a 32 bit . So when assigning 5 to char it fits in 16 bits so it's cool but int clearly is to large. Reference http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html – DotNetRussell Oct 19 '14 at 02:00
  • 2
    Integer.MAX_VALUE is 7fffffff, while a char can go up to '\uFFFF' – Hovercraft Full Of Eels Oct 19 '14 at 02:01
  • 5
    @Victor2748 The question you referred is different. He is pointing other thing. – afzalex Oct 19 '14 at 02:02
  • What part of the quote *Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:* isn't the answer to this? –  Oct 19 '14 at 02:07
  • Because the question is dealing with adding integer values to `char`, whereas this one is expressly dealing with conversions between `int` to `char`. – Makoto Oct 19 '14 at 02:10

2 Answers2

9

A char can be assigned to an int without a cast because that is a widening conversion. To do the reverse, an int to a char requires a cast because it is a narrowing conversion.

See also JLS. Chapter 5. Conversions and Promotions.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
6

His question is why his code does not compile, not how to do what he's trying to do.

The reason the line

char c = n

does not compile, is because the range of char (-2^15 to 2^15 - 1) is much smaller than the range of int (-2^31 to 2^31 - 1). The compiler sees you are trying to assign an int to a char, and stops you, because it realizes this.

Tetramputechture
  • 2,911
  • 2
  • 33
  • 48