0
for(int i=0; i < 26; i++) {

alphabet[i] = (char)('a' + i);

hello, please explain what does the second line mean. Is it type casting from char to int?

Harshal Patil
  • 6,659
  • 8
  • 41
  • 57
omkar
  • 216
  • 2
  • 10
  • 2
    `'a' + i` is an `int`; `(char) 'a' + i` casts the `int` back to a `char`. – Andy Turner Feb 19 '17 at 15:14
  • 2
    Possible duplicate of [Java - char, int conversions](http://stackoverflow.com/questions/21317631/java-char-int-conversions) – azro Feb 19 '17 at 15:15
  • 1
    *"Is it type casting from char to int?"* No, it's typecasting from `int` (the result of `'a' + i`) to `char`. – T.J. Crowder Feb 19 '17 at 15:16

3 Answers3

1

When you perform arithmetic operations in data types shorter than int for example, shorts, bytes and chars, the end result of the operation is returned as an int.

Thus in your case 'a' +i is an operation on char and int. So the result is an int.

So if you want a character back from this operation it is mandatory for you to perform an explicit cast.

So the operation here is a type cast from int to char.

anacron
  • 6,443
  • 2
  • 26
  • 31
0

It is a cast from int to char. Addition of int and char ('a' + i) make the expression of wider type.

lukeg
  • 4,189
  • 3
  • 19
  • 40
0

Thanks I came to know it is typecasting syntax it has to be written in that manner.

omkar
  • 216
  • 2
  • 10