This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes charAt Assignments Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "charAt Assignments" Watch "charAt Assignments" New topic

charAt Assignments

Joshua Smith
Ranch Hand

Joined: Aug 22, 2005
Posts: 193

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?


Rational Pi Blog - Java, SCJP, Dev Bits-
raghu babu
Ranch Hand

Joined: Jul 05, 2005
Posts: 60
charAt(int i) function's return type is char.

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
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.

I agree. Here's the link:
subject: charAt Assignments