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 int assignment to a char variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "int assignment to a char variable" Watch "int assignment to a char variable" New topic
Author

int assignment to a char variable

Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787

Why is that line 1 does not give compiler error but line 2 does. In both cases RHS is an int and LHS is a char.
[ October 07, 2002: Message edited by: Barkat Mardhani ]
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
On line 1, 2 is a int literal within the bounds of the values allowed for a char (0,65535). The compiler does not object.
On line 2, c is first converted to an int, then incremented by one. The result of c + 1 has to be downcast to a char in order to be allowed to assign it to c again. Check out JLS 5 Conversions and Promotions for details.


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787
posted by

On line 1, 2 is a int literal within the bounds of the values allowed for a char (0,65535). The compiler does not object.
On line 2, c is first converted to an int, then incremented by one. The result of c + 1 has to be downcast to a char in order to be allowed to assign it to c again. Check out JLS 5 Conversions and Promotions for details.

But c+1 is also within the range of char. I guess only it can be safely said that an implicit cast will be applied (if needed) when:
1. RHS is composed of only literals and final variables
2. RHS is within the range of LHS type.
Following compiles:

Is this correct understanding?
Thanks
Barkat
[ October 07, 2002: Message edited by: Barkat Mardhani ]
[ October 08, 2002: Message edited by: Barkat Mardhani ]
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
If the value can be determined at compile time (literal or final values), then no cast is needed, otherwise the cast is needed. Remeber that the compiler does not execute the code, and thus, cannot know that c+1 is within the range of chars.
JLS 5.2 Assignment Conversion provides some insights
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: int assignment to a char variable