Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt with assignment

 
Asha K
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Rajith Vidanaarachchi
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic