Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 581
gizgok Avatar asked Dec 15 '11 10:12

gizgok


1 Answers

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.

like image 133
Joonas Pulakka Avatar answered Oct 09 '22 08:10

Joonas Pulakka