• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Doubt with assignment

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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;
^
 
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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;
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic