0

I'm currently struggling to understand why this expression

        String test = new String("hello");
        char y = test.charAt(0) - '0';

is not counted as compile-time constant expression and yields the error

error: incompatible types: possible lossy conversion from int to char
                char y = test.charAt(0) - '0';

but this expression does compile

        String test = new String("hello");
        char[] charArr = test.toCharArray();
        char y = (char) (charArr[0] - '0');

As my current understanding right now upon defining the String variable I've already declared a compile-time variable. I am simply just retrieving the character at the specified index of test, then do some arithmetic operation on it.

Is this caused by the inner working of the String.charAt(index) function? Or is it because of the Java language feature? Or it is caused entirely by something else? May I have some clarification on this or further reading resources? Thank you.

Chass Long
  • 539
  • 4
  • 16
  • This has nothing to do with compile-time constants or even String. You want to "press" a "bigger" variable type into a "smaller" one and Java warns you about that. – Tom Jun 17 '21 at 01:57
  • @Tom It kind of does. You *can* press a bigger type into a smaller one if it is a compile time constant. – Sweeper Jun 17 '21 at 01:58
  • 1
    The second code compiles because you are doing a cast (`(char)x`), not because it's a compile time constant (it's not). Neither are compile time constant expressions, because the things that the compiler can evaluate at compile time are very limited. `charAt` and `toCharArray` are just two regular old methods as far as the compiler is concerned. It doesn't know that it has enough information to evaluate them at compile time. – Sweeper Jun 17 '21 at 02:00
  • See also: https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28 – Sweeper Jun 17 '21 at 02:04

0 Answers0