1

In Java I know you can convert char to ints like so:

int c = (int) msg.charAt(i);

But why does this also work with no errors:

int c = msg.charAt(i);

the function returns an int, so surely it needs to be "cast" to an int before using it.

DUPLICATE: Although the answer given by: Why are we allowed to assign char to a int in java? , the qusestion is slightly different. As I was not asking why we can assign a char to an int, rather I was asking why no cast is necessary. I'll suggest to keep this open for people on Google, even though its the same answer!

Community
  • 1
  • 1
Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231
  • This will compile, but if you have to do calculation with this value, it will give you a wrong result. I'm just talking from my C# experience :) – JustAPup Mar 23 '15 at 15:13
  • The question is interesting but I had to mark it as duplicate. Just know that assigning `char` to `int` is allowed in C and was therefore allowed in Java. – Arnaud Denoyelle Mar 23 '15 at 15:15
  • @Minh I knew it compiles. I just wanted to know why it worked? thanks for the answer though. – Yahya Uddin Mar 23 '15 at 15:20
  • 1
    A `char` has a value between 0 and 65535. An `int` has a value between -2,147,483,648 and 2,147,483,647. As there is no possibility that "significance" will be lost doing the conversion, it happens automatically. When a cast is used you're acknowledging that you know "overflow" may occur and you're accepting responsibility for that possibility. – Hot Licks Mar 23 '15 at 15:45

1 Answers1

1

String.charAt returns char. char to int is a widening primitive conversion (see JLS 5.1.2), this type of conversion does not lose information so it does not need an explicit cast

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275