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
You could cast
char temp = (char) (text.charAt(0) + 1);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With