Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

incrementing char values from .charAt function

Tags:

java

char

fairly simple question

char temp = 'a' + 1

works correctly returning 'b' however

char temp = text.charAt(0) + 1 (text is a string consisting only of letters)

returns an error stating incompatible types despite the .charAt function returning a char - any solution or workaround

like image 494
Tytey Avatar asked Sep 17 '26 22:09

Tytey


2 Answers

You could cast

char temp = (char) (text.charAt(0) + 1);
like image 53
Reimeus Avatar answered Sep 20 '26 11:09

Reimeus


char temp = 'a' + 1 It works because it converts constant int to char.

char temp = text.charAt(0) + 1 It doesn't work because it converts int to char.

You should implicitly cast into char. char temp = (char)text.charAt(0) + 1 or char temp = (char)text.charAt(0); temp++

This is a special case. Java allows implicit narrowing casting. It is only when assigning a constant expression to a smaller type. Its value must fit with the target type's range.

'a' + 1 is a compile-time constant (97 + 1 = 98). 98 fits within the char range (0 to 65535).

like image 42
peter8015 Avatar answered Sep 20 '26 10:09

peter8015