• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java in general

 
sarada chellu
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can any one explain why line 2 is illegal ?
char c='a';
int i=10;
c+=i;// Legal line 1
c=c+i; //illegal line 2
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When using mathematical operations, the result is always the larger of the two operands, but never smaller than int. So int + int = int, int + long = long, char + int = int, char + char = int.
The only way to break this is by using the +=, -= etc operators. This forces the right hand side to be cast to the same type as the left hand side.

So c += i is short hand for c = (char)(c + i) but c = c + i will fail because the result of c + i is an integer and you cannot assign an integer to a char variable without explicit casting.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15205
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"sarada ch", please check your e-mail for a message from JavaRanch.

The second line is illegal because the type of the result of the expression on the right-hand side, 'c + i', is int, and you cannot assign an int to a char without a cast.
 
sarada chellu
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks prime !
It's clear for me now. :-)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic