• Post Reply Bookmark Topic Watch Topic
  • New Topic

adding int to char  RSS feed

 
Daniel .J.Hyslop
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
here`s a really small bit of code,

[code]
public class Test
{
public static void main(String[] args)
{
char c = 'c';
int i = 1;

c+=i;//this part compiles
c=c+i;//this causes a compiler error?
}
}
in the above class it seems to me that both statements should create the same output ,as both statements are adding 1(one) to char c which should result in 'c' becoming 'd' .If I remove c=c+i;the program compiles OK .Why does c=c+i cause a compiler error and the other does`nt.I was just doing some revision of previous topics and found this and can`t figure it out.So I appologise if it is a simplistic problem,and thanks in advance for any help.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you search in the Java Language Specification, you'll actually find that the += operator includes an implicit cast that's not there when you use just + -- i.e., "c += i" is not equivalent to "c = c + i" but to "c = (char) (c + i)". This goes for all of the "X=" operators.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!