简体   繁体   中英

Why does char to int casting works and not char to Integer in Java

I was working on a problem when I encountered this.

(int)input.charAt(i) //works
(Integer)input.charAt(i) // Does not work
// input being a string

The first thought I have is primitives are treated differently and that is why this is not working. But then I find it difficult to understand why would they have a Integer Wrapper class in the first place.

Edit: What are the advantages of having wrapper classes then? Is it just for not having a primitives presence and being more OO in design? I'm finding it difficult to understand how are tehy helpful. New doubt altogetehr.

You're right that primitives are treated differently. The following would work:

(Integer)(int)input.charAt(i);

The difference is that when the argument is an int , (Integer) boxes the integer. It's not actually a cast even though it looks like it. But if the argument is a char , then it would be a cast attempt; but primitives can't be cast to objects and therefore it doesn't work. What you can do is to first cast the char to int - this cast is okay since both are primitive types - and then the int can be boxed.

Of course, char -> Integer boxing could have been made working. "Why not?" is a good question. Probably there would have been little use for such feature, especially when the same function can be achieved by being a little bit more explicit. (Should char -> Long work too, then? And char -> Short ? chars are 16-bit, so this would be most straightforward.)

Answer to edit: the advantage of wrapper classes is that wrapped primitives can be treated like objects: stored in a List<Integer> , for example. List<int> would not work, because int is not an object. So maybe even more relevant question would be, what are primitive non-objects doing in an OO language? The answer is in performance: primitives are faster and take less memory. The use case determines whether the convenience of objects or the performance of primitives is more important.

Because Integer is an Object . and char is not. you cant cast a non Object thing to some Object.

Infact you cannot cast some Object to any other class Object which is not in the hierarchy of that Object.

eg you cannot do this

Integer g = (Integer) s;

where s is object of String .

Now why chat to int works, because every character is represented as unicode in java, so you can think of it as at backend char is a smaller version of int. (int is 32 bits and char is 16 bits)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM