Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What's the difference "c=c+1" vs "c+=1"

 
Sam Bai
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code below can print out 'b'
char c='a';
c+=1;
System.out.println(c);
Why the code below cannot compile?
char c='a';
c=c+1;
System.out.println(c);
Thanks a lot!
 
Saniya Ansari
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is because when u do the operation c + 1 the c is converted to int to carry out the opeartion. To assign it back to a char type u need to have an explicit cast since int is a 32 bit data type while char is 16 bit.
In the extended operators this is done automatically. Coz the extenede operator looks like this: c= (char)(c+1); so this will do the job.
Hope this will be of help!
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Heng630,
Welcome to Javaranch
We'd like you to read the Javaranch Naming Policy and change your publicly displayed name (change it here) to comply with our unique rule. Thank you.
PS: Quote from the naming policy:

For your publicly displayed name, use a first name, a space, and a last name. Obviously fictitious names or improperly formatted names may be locked out.
 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
posted by Saniya:

This is because when u do the operation c + 1 the c is converted to int to carry out the opeartion. To assign it back to a char type u need to have an explicit cast since int is a 32 bit data type while char is 16 bit.

Furthermore, the mentioned explicit cast can be avoided if RHS is composed of literals and/or final variables which results in a value that is within the range of LHS type. See following code which compiles o.k.:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic