A dumb question about primitives

Ok so there might be a real good answer to this question but I don't get it : Why did Sun bother with primitives and not just give us the Object based wrapper classes ?
[183 byte] By [Haclanda] at [2007-10-2 6:34:40]
# 1

Because Java was largely based on C and C++, in which there are primitives just like Java.

In Java 5 there is [url=http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html]autoboxing[/url], but that does not mean you should replace all your primitives with instances of the wrapper classes - that would be terribly inefficient.

jesperdja at 2007-7-16 13:36:58 > top of Java-index,Java Essentials,New To Java...
# 2
I thought it would be something to do with efficiency. But doesn't it make more sense to treat everything as an object derived from java.land.Object ?
Haclanda at 2007-7-16 13:36:58 > top of Java-index,Java Essentials,New To Java...
# 3
You're on the right track. Aside from the historical reasons, efficiency is another consideration. Objects come with overhead that (sometimes) is too costly. It's a tradeoff.
Dick_Adamsa at 2007-7-16 13:36:58 > top of Java-index,Java Essentials,New To Java...
# 4

here is what James Gosling had to say on this. I quote:-

Bill Venners: Why are there primitive types in Java? Why wasn't everything just an object?

James Gosling: Totally an efficiency thing. There are all kinds of people who have built systems where ints and that are all objects. There are a variety of ways to do that, and all of them have some pretty serious problems. Some of them are just slow, because they allocate memory for everything. Some of them try to do objects where sometimes they are objects, sometimes they are not (which is what the standard LISP system did), and then things get really weird. It kind of works, but it's strange.

Just making it such that there are primitive and objects, and they're just different. You solve a whole lot of problems.

kilyasa at 2007-7-16 13:36:58 > top of Java-index,Java Essentials,New To Java...
# 5

I agree that with the way Java works now it would be very inefficient to use instances the wrapper classes instead of primitives, because it would mean you would have to do everything via references (you wouldn't have "direct" variables, which the primitives are) - so for every Integer, Char, Long etc. Java would need to allocate space on the heap, and you can only access it via references.

However, there's no reason why the Java compiler couldn't optimize all that overhead away. The Java compiler writers could treat the wrapper classes as "special" and convert them to primitives behind the scenes, and it would work just as efficiently as the primitives as we use them now in Java.

In Java 5, with autoboxing and -unboxing, the wrapper classes are already treated specially, but it's not done all the way. Maybe in a future Java version?

jesperdja at 2007-7-16 13:36:58 > top of Java-index,Java Essentials,New To Java...