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
posted
0
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
posted
0
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.
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.: