Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char and int in Java

Tags:

java

I was surprised to see this code work. I thought that char and int were two distinct data types in Java and that I would have had to cast the char to an int for this to give the ascii equivelent. Why does this work?

String s = "hello";
int x = s.charAt(1);
System.out.println(x);
like image 433
Roger Avatar asked Dec 18 '11 02:12

Roger


2 Answers

A char can be automatically converted to an int. See JLS 5.1.2:

The following 19 specific conversions on primitive types are called the widening primitive conversions:

...

  • char to int, long, float, or double

...

A widening conversion of a signed integer value to an integral type T simply sign-extends the two's-complement representation of the integer value to fill the wider format. A widening conversion of a char to an integral type T zero-extends the representation of the char value to fill the wider format.

(emphasis added)

like image 138
yshavit Avatar answered Oct 17 '22 01:10

yshavit


char and int are two distinct types, but this works because an int has more precision than a char. That is, every value of char can be represented as an int so no data is lost in the cast.

like image 22
Kevin Avatar answered Oct 17 '22 00:10

Kevin