File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Doubt with assignment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt with assignment" Watch "Doubt with assignment" New topic

Doubt with assignment

Asha K

Joined: Feb 17, 2000
Posts: 2
public class T {
public static void main(String [] args) {
int myInt = 1;
char myChar = 'c';
myInt = myChar; //works
myChar=98; //works
myChar = myInt;//Does not work. Why?
} Incompatible type for =. Explicit cast needed to convert int to char.
myChar = myInt;
Sridhar Garimella
Ranch Hand

Joined: Feb 18, 2000
Posts: 73
Hi Asha,
According to my opinion the answer for u r question is like this.

myChar c=98//no problem because you are assigning literal.

in the next case you are assinging like this
here you are assigning a variable of type int to a variable of type char.But in java implicit conversion has done from smaller data types to larger data types i.e., char to int but for viceversa you have to cast explicitly.For that you get compilation error.
sreedhar garimella(

Thanks,<br />Sridhar.
Rajith Vidanaarachchi

Joined: Nov 06, 2004
Posts: 11
Hi Asha,

A char is 16 bit but a int is 32 bit so we can't put an int into a char. To do so we need a cast. Try doing like this
int i=5;
char c =(char)i;
marc weber

Joined: Aug 31, 2004
Posts: 11343

Note that it's not only bits we're concerned with -- it's also range. A char does not contain negative values, so it has a greater range of positive values than a signed type of the same size. So even though a char and a short are both 16 bits, we cannot automatically convert between the two.

16-bit short range: -2^15 to 2^15 - 1.
16-bit char range: 0 to 2^16 - 1.
[ December 20, 2004: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link:
subject: Doubt with assignment
It's not a secret anymore!