Why do people still use primitive types in Java?

Effective Java, Item 5: "Avoid creating unnecessary objects.

Effective Java, Item 5: "Avoid creating unnecessary objects" He posts the following code public static void main(String args) { Long sum = 0L; // uses Long, not long for(long I = 0; I java biziclop false false true false C:\Documents and Settings\glow\My Documents.

4 Wow, EPIC autoboxing FAIL. – TK Kocheran Mar 4 '11 at 21:29 13 Now imagine if I were declared as Long as well! – ColinD Mar 4 '11 at 21:39 4 @TREE - the spec actually requires VMs to create flyweights within a certain range.

But sadly it allows them to extend that range, meaning that programs may behave differently on different VMs. So much for cross platform... – Daniel Earwicker Mar 5 '11 at 13:38 3 Java has gone down the drain, with more and more bad design choices. Autoboxing is a complete failure, it's neither robust, predictable or portable.

I really really wonder what they were thinking ... instead of fixing the dreaded primitive-object duality they managed to make it worse than in the first place. – Pop Catalin Mar 6 '11 at 18:33 6 @Catalin I disagree with you that autoboxing is a complete failure. It has some flaws, which is no different than any other design that could have been used (including nothing.) They make very clear what you can and can't expect, and like any other design they expect developers to know and obey the contracts of those designs.

– glowcoder Mar 6 '11 at 20:32.

Autounboxing can lead to hard to spot NPEs Integer in = null; ... ... int I = in; // NPE at runtime In most situations the null assignment to in is a lot less obvious than above.

1 Definitely a thorn in the side for Java programs, and sage advice. – John K Mar 5 '11 at 4:19.

Primitive types: int x = 1000; int y = 1000; Now evaluate: x == y It's true. Hardly surprising. Now try the boxed types: Integer x = 1000; Integer y = 1000; Now evaluate: x == y It's false.Probably.

Depends on the runtime. Is that reason enough?

– Daniel Earwicker Mar 4 '11 at 21:26 Interesting. I was always taught "use equals(), use equals(), use equals()!", so I hadn't really considered this. – TK Kocheran Mar 4 '11 at 21:28 6 You don't consider using meaningful syntax for actual arithmetic?

– poke Mar 5 '11 at 4:13.

Boxed types have poorer performance and require more memory.

First and foremost, habit. If you've coded in Java for eight years, you accumulate a considerable amount of inertia, however you try to fight it. The other reason is to assert that null is not a vaild option.It would be pointless and misleading to declare the sum of two numbers or a loop variable as Integer.

There's the performance aspect of it too, but more often than not that's just used as an excuse for habit. The performance difference very rarely actually matters.

5 I disagree. The performance aspect can be critical. Very little of this is probably inertial or force of habit.

– Eddie Mar 4 '11 at 21:26 2 @Eddie It can be, but it very rarely is. Trust me, for most people performance arguments are just an excuse. – biziclop Mar 4 '11 at 21:35 1 +1 for mentioning the "assert that null is not a valid option" case.

I was explaining this to a colleague earlier today. – D. Shawley Mar 5 '11 at 2:01.

Primitive types are much faster: int i; i++; Integer (all Numbers and also a String) is an immutable type: once created it can not be changed. If I was Integer, than i++ would create a new Integer object - much more expensive in terms of memory and processor.

You don't want one variable to change if you do i++ on another variable, so Integer quite needs to be immutable to be able to do this (or at least this i++ would have to create a new Integer object anyway). (And the primitive values are immutable, too - you just don't remark this since they are no objects. ) – Pa?

Lo Ebermann Mar 4 '11 at 22:00 @Pa? Lo: Saying that primitive values are immutable is kind of meaningless. When you reassign a primitive variable to a new value, you are not creating anything new.No memory allocation is involved.

Peter's point stands: i++ for a primitive does no memory allocation, but for an object it necessarily does. – Eddie Mar 5 '11 at 0:09 @Eddie: (It does not necessarily need memory allocation, it could also return a cached value. For some small values it does, I think.

) My point was that the immutability of Integers here is not the deciding point, you would anyway want to have another object, regardless of immutability. – Pa? Lo Ebermann Mar 5 '11 at 0:15 @Pa?

Lo: my only point was that Integer is an order of magnitude slower then primitives. And this is due to the fact that boxed types are immutable and every time you have change a value a new object is created. I did not claim there is something wrong with them or the fact that they are immutable.

Just that they are slower and that a coder should know that. Take a look at how Groovy fares without primitive types jroller.com/rants/entry/why_is_groovy_so_slow – Peter Knego Mar 5 '11 at 7:34 Immutability and ++ is a red herring here. Imagine Java was enhanced to support operator overloading in a really simple way, such that if a class (such as Integer has a method plus, then you could write I + 1 instead of i.

Plus(1). And assume also that the compiler is smart enough to expand i++ into I = I + 1. Now you could say i++ and effectively "increment the variable i" without Integer being mutable.

– Daniel Earwicker Mar 5 '11 at 10:25.

By the way, Smalltalk has only objects (no primitives), and yet they had optimized their small integers (using not all 32 bits, only 27 or such) to not allocate any heap space, but simply use a special bit pattern. Also other common objects (true, false, null) had special bit patterns here. So, at least on 64-bit JVMs (with a 64 bit pointer namespace) it should be possible to not have any objects of Integer, Character, Byte, Short, Boolean, Float (and small Long) at all (apart from these created by explicit new ...()), only special bit patterns, which could be manipulated by the normal operators quite efficiently.

1 +1 Very interesting recommendation based on the implementation of Smalltalk. I'm always intrigued by the experience and resulting ingenuity of many people around here. – John K Mar 5 '11 at 4:17 I should have said "some implementations", as this is not governed by the language specifications, I think.(And sadly I can't cite any sources here, it is only from what I heard somewhere.

) – Pa? Lo Ebermann Mar 5 '11 at 11:08? Lo, JIT already keeps meta into in the pointer; incl, the pointer can keep GC info, or the Klass (optimizing Class is a lot better idea than optimizing Integers, for which I can care less).

Changing the pointer would require, shift/cmp/jnz code (or something like that) before each pointer load. The branch probably won't be very well predicted by the hardware (since it can be both Value Type and normal Object) and it would lead to performance hit. – bestsss Mar 11 '11 at 6:24.

Can you really imagine a for (int i=0; iInteger is immutable, so each increment round the loop would create a new java object on the heap, rather than just increment the int on the stack with a single JVM instruction. The performance would be diabolical. I would really disagree that it's much mode convenient to use java.lang.

Integer than int. On the contrary. Autoboxing means that you can use int where you would otherwise be forced to use Integer, and the java compiler takes care of inserting the code to create the new Integer object for you.

Autoboxing is all about allowing you to use an int where an Integer is expected, with the compiler inserting the relevant object construction. It in no way removes or reduces the need for the int in the first place. With autoboxing you get the best of both worlds.

You get an Integer created for you automatically when you need a heap based java object, and you get the speed and efficiency of an int when you are just doing arithmetic and local calculations.

Objects are much more heavyweight than primitive types, so primitive types are much more efficient than instances of wrapper classes. Primitive types are very simple: for example an int is 32 bits and takes up exactly 32 bits in memory, and can be manipulated directly. An Integer object is a complete object, which (like any object) has to be stored on the heap, and can only be accessed via a reference (pointer) to it.It most likely also takes up more than 32 bits (4 bytes) of memory.

That said, the fact that Java has a distinction between primitive and non-primitive types is also a sign of age of the Java programming language. Newer programming languages don't have this distinction; the compiler of such a language is smart enough to figure out by itself if you're using simple values or more complex objects. For example, in Scala there are no primitive types; there is a class Int for integers, and an Int is a real object (that you can methods on etc. ).

When the compiler compiles your code, it uses primitive ints behind the scenes, so using an Int is just as efficient as using a primitive int in Java.

I would have assumed that the JRE would be "smart" enough to do this with Java wrapped primitives as well. Fail. – TK Kocheran Mar 4 '11 at 21:26.

In addition to what others have said, primitive local variables are not allocated from the heap, but instead on the stack. But objects are allocated from the heap and thus have to be garbage collected.

1 Sorry, this is wrong. A smart JVM can do escape analysis on any object allocations and, if they cannot escape, allocate them on the stack. – rlibby Mar 4 '11 at 21:31 1 Yes, this is beginning to be a feature of modern JVMs.In five years, what you say will be true for most JVMs then in use.

Today it is not. I almost commented about this, but decided to not comment on it. Perhaps I should have said something.

– Eddie Mar 4 '11 at 21:33.

It's hard to know what kind of optimizations are going on under the covers. For local use, when the compiler has enough information to make optimizations excluding the possibility of the null value, I expect the performance to be the same or similar. However, arrays of primitives are apparently very different from collections of boxed primitives.

This makes sense given that very few optimizations are possible deep within a collection. Furthermore, Integer has a much higher logical overhead as compared with int: now you have to worry about about whether or not int a = be + c; throws an exception. I'd use the primitives as much as possible and rely on the factory methods and autoboxing to give me the more semantically powerful boxed types when they are needed.

I can't believe no one has mentioned what I think is the most important reason: "int" is so, so much easier to type than "Integer". I think people underestimate the importance of a concise syntax. Performance isn't really a reason to avoid them because most of the time when one is using numbers is in loop indexes, and incrementing and comparing those costs nothing in any non-trivial loop (whether you're using int or Integer).

The other given reason was that you can get NPEs but that's extremely easy to avoid with boxed types (and it is guaranteed to be avoided as long as you always initialize them to non-null values). The other reason was that (new Long(1000))==(new Long(1000)) is false, but that's just another way of saying that ". Equals" has no syntactic support for boxed types (unlike the operators , =, etc), so we come back to the "simpler syntax" reason.

I think Steve Yegge's non-primitive loop example illustrates my point very well: sites.google.com/site/steveyegge2/langua... Think about this: how often do you use function types in languages that have good syntax for them (like any functional language, python, ruby, and even C) compared to java where you have to simulate them using interfaces such as Runnable and Callable and nameless classes.

Because, They map to hardware... I had to say it. Besides, Similar questions truly prove how bad the average developer is nowadays. Pity.

Thanks. – TK Kocheran Mar 10 '11 at 19:52 no, sarcasm, you're most welcome. It's said above is true – bestsss Mar 10 '11 at 21:36.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions