This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt with assignment" Watch "Doubt with assignment" New topic
Author

Doubt with assignment

Asha K
Greenhorn

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?
}
}
T.java:7: 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
myInt=1
myChar=myInt
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.
bye
sreedhar garimella(sreedhar_gari@hotmail.com)


Thanks,<br />Sridhar.
Rajith Vidanaarachchi
Greenhorn

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
Sheriff

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
sscce.org
 
 
subject: Doubt with assignment
 
Similar Threads
Char into Integer
how to print ASCII value of a number ?
MindQ test ERROR Q 14 !!!!!!!!!!!!?
Cast conversion
Converting an int to a char