File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
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: 19794
    
  20

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: 14435
    
  23

"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 8 API documentation
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