File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

charAt Assignments

 
Joshua Smith
Ranch Hand
Posts: 193
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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?

Thanks,
Josh
 
raghu babu
Ranch Hand
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 193
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks,
Josh
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic