简体   繁体   中英

How does String charAt() method work in Java?

Why does the following code create compile error? Doesn't charAt() method return char datatype?

public static void main (String[] args) throws java.lang.Exception
{
    String a = "abcd";
    char c = a.charAt(2)-'a';
}

error: incompatible types: possible lossy conversion from int to char

When you subtract two char s, they are promoted to int and the subtraction is performed on two int operands, and the result is an int .

You can cast to char to assign the result to a char :

char c = (char) (a.charAt(2)-'a');

Note that you might get unexpected results if the subtraction results in a negative value, since char can't contain negative values.

Besides, I'm not sure it makes any sense to subtract 'a' from a character and store the result in a char . In your example, it will give you the character whose numeric value is 2, which has no relation to the character 'c'.

Java Language Specification says:

  • If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed. Then:
  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.

  • Otherwise, both operands are converted to type int.

So you need to explicitly cast it to char to get rid of the possible lossy error

char c = (char) (a.charAt(2)-'a');

Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (§5.1.13) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.

charAt() method return char type But you are subtracting two char that will return int value in this case it will be 2 . So receive it into int it will work.

int c = a.charAt(2)-'a';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM