It's not a secret anymore!*
The moose likes Beginning Java and the fly likes Java in general Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java in general" Watch "Java in general" New topic
Author

Java in general

sarada chellu
Greenhorn

Joined: Sep 25, 2007
Posts: 17
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

Joined: Oct 27, 2005
Posts: 19651
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

"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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
sarada chellu
Greenhorn

Joined: Sep 25, 2007
Posts: 17
Thanks prime !
It's clear for me now. :-)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Java in general
 
Similar Threads
Compile time Difference between // and /* */
event handling problem
casting problem(new) !!!
Getting compilation error while running axis web service
Casting problem !!!!!!