tags:

views:

117

answers:

4

We have wrapper classes in java like Interger, Float.. why it is still supportng primitives which is stoppting java to be fully object oriented language?

+2  A: 

http://en.wikipedia.org/wiki/Backward_compatibility

compatibility with what?
Thilo
With existing code.
Humm, I thought both the primitives and the wrappers were there from the beginning?
Joonas Pulakka
That only explains why Java6 still has them, not why they made it into the Java language at all.
Thilo
Java was meant to be attractive to C++ programmers. Those people *love* primitives :)
Then it may pissed them that Java doesn't have word, short, long, etc
nanda
Those people also love unsigned types and pointers and pre-processors and templates.
Thilo
+3  A: 

Because primitives are lighter and more efficient in term of memory and CPU processing.

nanda
And we must consider this while working with mobile/hand-held devices.
Adeel Ansari
But please also consider whether it has a 10 % or a 0.00001 % effect in a particular situation. Only optimize if it matters.
Joonas Pulakka
+2  A: 

One word: Performance.

The wrapper types are also immutable, which makes it extra expensive if one wanted to use one for a loop counter, for example.

The JVM also has opcodes for directly doing arithmetics on primitives.

Thilo
+6  A: 

Wrappers, being objects, get placed in the heap. Primitives are just "values" and go in the stack. This is more efficient, because for wrapped primitives in the heap you need (at least) both the value (which is in the stack) and the reference to the wrapper object.

Whether this performance gain matters at all depends on what you're doing. For heavy numerical work, definitely, but for 99 % of stuff out there, this is rather an annoyance. For one thing, you can't store primitives in a Collection anyway; they get autoboxed. So the only way to store lots of them is to use plain arrays, which in turn can lead to other kinds of inefficiencies (if you need to resize them, for instance).

Joonas Pulakka
are there any others reasons than storage?
GK
I'm not 100% sure about how the internals work here, but I believe that to calculate anything with the numbers, the machinery has to first extract the values from the wrappers (unboxing), which takes at least some work. But the JIT runtime optimization is probably playing its tricks here, so the difference may be quite negligible in practice, even in numerically intensive programs. This should be measured to be sure.
Joonas Pulakka