General discussion

Locked

char assignments

By steverichman ·
given the following:

public class CharTest {
public static void main (String args[ ])
{
char c = 'c';
char r = 'r';
c+=r;
c=c+r;
}
}

How come c+=r; compiles, yet c=c+r; doesn't, complaining about a possible loss of precision by widening r to an int?
Isn't the += operator just a shorthand notation?

This conversation is currently closed to new comments.

3 total posts (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

char assignments

by kris.verbeeck In reply to char assignments

I also thought that the two are equivalent. I checked the Java Lang Spec 1.0, and in there it is stated (section 5.6.2) that the promotion from char to int is necessary for the '+' operator, but not for '+='. So actually it is the correct behaviour, but a strange one nevertheless.

Although it might be logical, because the first statement is actually an assignment (a special one), and you can assign a char to a char. The second statement is an expression that is assigned to a variable. And math with chars is done as ints.

Collapse -

char assignments

by steverichman In reply to char assignments

Poster rated this answer

Collapse -

char assignments

by steverichman In reply to char assignments

This question was closed by the author

Back to Web Development Forum
3 total posts (Page 1 of 1)  

Related Discussions

Related Forums