int to char

ok....

i know i can convert from int to char using something like this..

System.out.println((char)65);

but when i want to do something like....

Integer as = 65;

System.out.println((char)as);

then it give me...

/media/hda2/mjalan/Documents/wizard/Wizard.java:421: inconvertible types

found: java.lang.Integer

required:char

System.out.println((char)as);

1 error

now, i am quite confused what i have done wrong since i only change the number to a variable.....

Thanks for any help!

[697 byte] By [mjalana] at [2007-10-2 11:24:03]
# 1
You cannot convert an "Integer" to a char. You must convert the Integer to an int first. A simple cast will do this with autounboxing.Integer as = 65;println((char)(int)as);
Laszlo.a at 2007-7-13 4:28:43 > top of Java-index,Java Essentials,Java Programming...
# 2
Integer is a wrapper class you cant cast instances of class Integer in to char you have to use int instead
LRMKa at 2007-7-13 4:28:43 > top of Java-index,Java Essentials,Java Programming...
# 3

That's because there's a difference between an int and an Integer. One is a primitive and the other an object.

In addition there's a mechanism called autoboxing which atomatically converts between int and Integer.

Appearantly as in the println statement is interpreted as an object. You can do either of these,

int as = 65;

System.out.println((char)as);

or

Integer as = 65;

System.out.println((char)as.intValue());

LRMKa at 2007-7-13 4:28:43 > top of Java-index,Java Essentials,Java Programming...
# 4

You can't cast an Integer to a char.

int is a primitive Type whereas Integer is an Object.

int intValue = 65;

Integer integerValue = new Integer(65);

// that's possible

char chr = (char) intValue;

// that's also possible

chr = integerValue.intValue();

// that does not compile

chr = (char) integerValue;

andiha at 2007-7-13 4:28:43 > top of Java-index,Java Essentials,Java Programming...
# 5
> You can do either of> these,Or the third one Laszlo suggested. -:)In anyways it pays off to know about the autoboxing conversion that's going on in the background. If you use Eclipse you can get it to warn you when such things happen.
andiha at 2007-7-13 4:28:43 > top of Java-index,Java Essentials,Java Programming...
# 6
ah..... i see......thanks guys... it sorted my problem.. :D
mjalana at 2007-7-13 4:28:43 > top of Java-index,Java Essentials,Java Programming...