This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes What's the difference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "What Watch "What New topic
Author

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

Sam Bai
Greenhorn

Joined: Oct 07, 2002
Posts: 1
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

Joined: Sep 30, 2002
Posts: 48
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!


SCJP 2
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
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.


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 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.:
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What's the difference "c=c+1" vs "c+=1"