charAt Assignments

If assigning a char to a byte or a float is fine, why is extracting a character from a String literal and assigning to a byte illegal, but doing the same for a float is fine? I could understand it maybe if it was if the String was contained in a variable because the compiler wouldn't be able to determine what char might be extracted and it might be out of range for a byte, but this is a literal. Doesn't the compiler have everything it needs to check the range at compile time?

The result of this function is not a compile time constant, so it results in compile error.

in your example, byte b1 = 'a'; // fine

try this, char a = 'a'; byte b1 = a //you will get a compiler error

in case of float f2 = "a".charAt(0);

result of right hand side in the above assignment is of type char and gets promoted to int and then to float, which is not a problem.

Joshua Smith
Ranch Hand

Joined: Aug 22, 2005
Posts: 193

posted Aug 25, 2005 07:24:00

0

Ok. That makes sense.

I assumed that the compiler would be able to treat an operation like charAt on a String literal as a compile-time constant since Strings are immutable and nothing at runtime can change the outcome of the operation. I guess I pushed the definition of what can be considered a compile-time constant too far.