File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "charAt Assignments" Watch "charAt Assignments" New topic
Author

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?

Thanks,
Josh


Rational Pi Blog - Java, SCJP, Dev Bits- http://rationalpi.wordpress.com
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.

Thanks,
Josh
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: charAt Assignments