You are getting essential things wrong here.

First of all, writing a good micro-benchmark goes way beyond what you are doing in your code; see here for some guidelines.

Then: you have to understand the things you want to benchmark. For example:

public static long wrapper(Integer count)
{
  long startTime = System.currentTimeMillis();
  for(int i=0;i<10000;i++)
    count++

Integer objects are immutable. This code does not only "add" Integer objects, it creates one new Integer object per iteration.

And of course: your code doesn't even use the computation result. If the JVM/JIT notices that, it might completely throw away that looping and adding construct. So your methods should at least return the final value of count; and the caller should print that result.

And to answer your specific question: of course using the reference type wrapper classes comes at certain cost. When your program is dealing with (really) high numbers of elements to work on, then using a List of Integer does have considerable higher cost than using an array of int for example. And when you don't pay attention and you are doing implicit autoboxing/unboxing in your code, that can really hurt.

But the real answer here is: you are focusing on the wrong thing. You see, your first priority should be to do a great design, followed by a well-tested, robust, readable, maintainble implementation. Of course, you should not do outright stupid things and waste performance, but well, before you worry about performance, you better worry about your Java skills in general.

Long story short: focus on understanding java and on "how do I create a good design"; and forget about "performance" for now. You only have to deal with "performance" when it is a real issue in your application. And then you do real profiling in order to identify the root cause and fix that.

Answer from GhostCat on Stack Overflow
Top answer
1 of 1
13

You are getting essential things wrong here.

First of all, writing a good micro-benchmark goes way beyond what you are doing in your code; see here for some guidelines.

Then: you have to understand the things you want to benchmark. For example:

public static long wrapper(Integer count)
{
  long startTime = System.currentTimeMillis();
  for(int i=0;i<10000;i++)
    count++

Integer objects are immutable. This code does not only "add" Integer objects, it creates one new Integer object per iteration.

And of course: your code doesn't even use the computation result. If the JVM/JIT notices that, it might completely throw away that looping and adding construct. So your methods should at least return the final value of count; and the caller should print that result.

And to answer your specific question: of course using the reference type wrapper classes comes at certain cost. When your program is dealing with (really) high numbers of elements to work on, then using a List of Integer does have considerable higher cost than using an array of int for example. And when you don't pay attention and you are doing implicit autoboxing/unboxing in your code, that can really hurt.

But the real answer here is: you are focusing on the wrong thing. You see, your first priority should be to do a great design, followed by a well-tested, robust, readable, maintainble implementation. Of course, you should not do outright stupid things and waste performance, but well, before you worry about performance, you better worry about your Java skills in general.

Long story short: focus on understanding java and on "how do I create a good design"; and forget about "performance" for now. You only have to deal with "performance" when it is a real issue in your application. And then you do real profiling in order to identify the root cause and fix that.

🌐
Medium
konstantinmb.medium.com › understanding-primitive-types-and-wrapper-classes-in-java-a-comprehensive-guide-6013c6b1c87
Understanding Primitive Types and Wrapper Classes in Java: A Comprehensive Guide | by Konstantin Borimechkov | Medium
June 20, 2023 - Memory and Performance Optimization: If you are working with a large number of values or performance-critical scenarios, using primitive types can be more efficient. Working with Arrays: Primitive types can be used directly in arrays, which ...
Discussions

integer - What is the real difference between primitives and wrapper classes in Java - Stack Overflow
Thanks for sharing.Can you emphasise ... as both(primitives and wrappers) were designed at the same time from scratch? 2020-08-07T05:51:52.787Z+00:00 ... @Hardik The main issue in embedded systems is often CPU and RAM limitations. You can't have a big complicated VM in a toaster because it's not going to have a 2GHz processor and 16GB of RAM. The creators of Java didn't come ... More on stackoverflow.com
🌐 stackoverflow.com
java - Primitive variables perform calculations faster than their associated wrapper class - Stack Overflow
This is an exact statement from a book on Java. Can someone confirm whether this is indeed right ? And why does the operation cost done on wrapper classes will be higher than their primitive counterpart ? ... If the performance and memory usage was the same you wouldn't need primitives. More on stackoverflow.com
🌐 stackoverflow.com
java - When to use wrapper class and primitive type - Stack Overflow
When I should go for wrapper class over primitive types? Or On what circumstance I should choose between wrapper / Primitive types? More on stackoverflow.com
🌐 stackoverflow.com
When to use primitive vs class in Java? - Software Engineering Stack Exchange
I see that Java has Boolean (class) vs boolean (primitive). Likewise, there's an Integer (class) vs int (primitive). What's the best practice on when to use the primitive version vs the class? Should I basically always be using the class version unless I have a specific (performance?) reason not to? What's the most common, accepted way to use each? ... See SO: When to use wrapper ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
People also ask

Why do frameworks like Hibernate prefer wrappers over primitives?
Because wrappers can represent null, which is essential for database mapping.
🌐
prgrmmng.com
prgrmmng.com › home › series › java wrapper classes › comparing primitives and wrapper classes in java
Comparing Primitives and Wrapper Classes in Java | prgrmmng.com
🌐
Medium
medium.com › @vaibhav0109 › java-primitives-vs-wrapper-which-one-to-use-aa7d6efc024
Java Primitives vs Wrapper : Which one to use? | by Vaibhav Singh | Medium
January 27, 2020 - Above Image shows the performance impact, since primitives live on stack and as they are accessed faster than on heap their average execution time is pretty low in comparison to the corresponding wrapper object counter parts.
🌐
Prgrmmng
prgrmmng.com › home › series › java wrapper classes › comparing primitives and wrapper classes in java
Comparing Primitives and Wrapper Classes in Java | prgrmmng.com
September 11, 2025 - Java 9: Improved efficiency in Integer.valueOf caching. Java 17: JVM-level performance improvements. Java 21: No significant updates across Java versions for this feature. Primitives are fast, memory-efficient, and non-nullable.
Top answer
1 of 3
16

The real difference is that primitive types are not reference types.

In Java type system, reference types have a common root, while primitive types do not: All reference types are subtypes of Object. In comparison, primitive types do not have a common root; each primitive type is its own special unicorn.

This means that a variable declared with Object type can hold a value of any reference type, but it cannot hold a value of any primitive type.

This is a problem if you want to create data structures that are generally useful. Consider how you would implement a "dynamic array" data structure like ArrayList or Vector. You could use an array Object[] to store the elements, and that would work for all reference types. But since primitive types don't have a common root you would have to create a separate implementation for each primitive type.

To solve this problem, wrapper classes were created. Now, instead of needing 8 separate implementations of dynamic array (1 for reference types and 7 for primitive types), you could wrap each primitive value in an object, and just use the implementation for reference types.

Primitive types and wrapper classes were created at the same time, when the first design and implementation of Java 1.0 were made. The designers did not "reuse what was already available" because nothing was available: they built everything from scratch.

Could the designers have solved the problem some other way, maybe by creating a type system that had a common root for both primitive and reference types? Yes, but they didn't, and they probably had good reasons: implementation complexity, ease of understanding, time to market, ...

2 of 3
5

Actually, this question is pretty insightful. The answers are good and correct, but the underlying question that I think is worth asking is: should primitive types exist at all? We had a lot of discussion about this at the time and I think the reason things ended up the way they did had to do with the fact that Oak (later Java) was designed as an embedded language for the IOT (internet of things). If it had been originally designed as a server language, it might have been very different. I think primitive types are a legacy idea that is actually very harmful for exactly the reasons that Joni mentions. It's possible and desirable to have everything in the system extend Object.

How could you eliminate primitives? With a smarter JVM. HotSpot could turn special primitive objects into appropriate machine code wherever possible and there wouldn't be a need for autoboxing, wrappers or difficulties with the type system being split. The only limitation that I think would need to be placed on Integer, Float, Double, etc., is that they would have to be final. This would allow these classes to be optimized anywhere possible as if they were primitives without actually having primitives in the language. You could even have syntactic abbreviations like 'int', 'float' and 'double' for these special classes, but the important thing is that the type system would be better if it was fully unified.

But you don't start trying to build such a thing when you're thinking about smart toasters. What happened to Java in terms of its wild success was a pure accident. It happened to be a solution to a lot of web-related issues just sitting there at the right time. But it wasn't planned that way, so there are a lot of things people would like to have back. I think a lot of people at Sun/Oracle would eliminate primitives in hindsight.

Find elsewhere
🌐
Medium
medium.com › @hrutiksurwade › java-primitive-class-vs-wrapper-class-variables-77a499127574
Primitive Class vs Wrapper Class Variables | by Hrutik Surwade | Medium
March 24, 2025 - Advanced Features: They come with utility methods for parsing, converting, and manipulating values. Nullability: Unlike primitives, wrapper objects can have null values. ... When performance is critical (e.g., in loops or mathematical operations).
🌐
Hazriq's Dev Chaos
hazriqpedia.github.io › posts › java: primitive data types vs wrapper classes
Java: Primitive Data Types vs Wrapper Classes | Hazriq's Dev Chaos
September 27, 2025 - Java makes conversion between primitives and wrappers seamless. ... This is convenient, but can introduce performance overhead if overused.
🌐
Java Handbook
javahandbook.com › java-interviews › differences-between-primitives-and-wrappers
Difference Between Primitives And Wrappers - Java handbook
April 27, 2025 - Performance -> Primitive types are faster and more efficient than wrapper classes because they don’t involve the overhead of object creation or garbage collection. However, wrappers offer more functionality at the cost of performance.
🌐
javathinking
javathinking.com › blog › when-to-use-wrapper-class-and-primitive-type
When to Use Wrapper Classes vs Primitive Types: Key Scenarios Explained — javathinking.com
While autoboxing makes code concise, it’s important to weigh performance costs: Primitives: Small and efficient. For example, an int uses 4 bytes. Wrappers: Include object overhead (e.g., Integer uses ~16 bytes in Java, due to object headers ...
🌐
GeeksforGeeks
geeksforgeeks.org › java-i-o-operation-wrapper-class-vs-primitive-class-variables
Java I/O Operation – Wrapper Class vs Primitive Class Variables | GeeksforGeeks
November 15, 2022 - Primitive classes are faster when compared to wrapper classes. However, the wrapper class allows null values but the primitive class does not allow any null values. Wrapper classes help the Java program be completely object-oriented whereas ...
🌐
javathinking
javathinking.com › blog › java-primitive-types-int-vs-integer
Java int vs Integer: When to Use Primitive vs Wrapper Types in Java (Performance & Android Guide) — javathinking.com
In Java, one of the most fundamental distinctions developers encounter is between **primitive types** (like `int`) and their corresponding **wrapper classes** (like `Integer`). While both represent integer values, their behavior, use cases, and performance characteristics differ significantly.
🌐
LabEx
labex.io › questions › what-are-the-differences-between-primitive-and-wrapper-data-types-in-java-178548
What are the differences between primitive and wrapper data types in Java? | LabEx
Performance: Primitive data types are generally faster and more efficient than wrapper data types, as they require less memory and processing overhead. In summary, primitive data types are the fundamental data types in Java, while wrapper data ...
🌐
Baeldung
baeldung.com › home › java › core java › java primitives versus objects
Java Primitives Versus Objects | Baeldung
January 8, 2024 - As we’ve seen, the primitive types are much faster and require much less memory. Therefore, we might want to prefer using them. On the other hand, current Java language specification doesn’t allow usage of primitive types in the parametrized ...
Top answer
1 of 5
56

In Item 5, of Effective Java, Joshua Bloch says

The lesson is clear: prefer primitives to boxed primitives, and watch out for unintentional autoboxing.

One good use for classes is when using them as generic types (including Collection classes, such as lists and maps) or when you want to transform them to other type without implicit casting (for example Integer class has methods doubleValue() or byteValue().

Edit: Joshua Bloch's reason is:

// Hideously slow program! Can you spot the object creation?
public static void main(String[] args) {
    Long sum = 0L;
    for (long i = 0; i < Integer.MAX_VALUE; i++) {
         sum += i;
    }
    System.out.println(sum);
}

This program gets the right answer, but it is much slower than it should be, due to a one-character typographical error. The variable sum is declared as a Long instead of a long, which means that the program constructs about 2^31 unnecessary Long instances (roughly one for each time the long i is added to the Long sum). Changing the declaration of sum from Long to long reduces the runtime from 43 seconds to 6.8 seconds on my machine.

2 of 5
32

The standard practice is to go with the primitives, unless you're dealing with generics (make sure you are aware of autoboxing & unboxing!).

There are a number of good reasons to follow the convention:

1. You avoid simple mistakes:

There are some subtle, non-intuitive cases which often catch out beginners. Even experienced coders slip up and make these mistakes sometimes (hopefully this will be followed by swearing when they debug the code and find the error!).

The most commmon mistake is using a == b instead of a.equals(b). People are used to doing a == b with primitives so it's easily done when you're using the Object wrappers.

Integer a = new Integer(2);
Integer b = new Integer(2);
if (a == b) { // Should be a.equals(b)
    // This never gets executed.
}
Integer c = Integer.valueOf(2);
Integer d = Integer.valueOf(2);
if (c == d) { // Should be a.equals(b), but happens to work with these particular values!
    // This will get executed
}
Integer e = 1000;
Integer f = 1000;
if (e == f) { // Should be a.equals(b)
    // Whether this gets executed depends on which compiler you use!
}

2. Readability:

Consider the following two examples. Most people would say the second is more readable.

Integer a = 2;
Integer b = 2;
if (!a.equals(b)) {
    // ...
}
int c = 2;
int d = 2;
if (c != d) {
    // ...
}

3. Performance:

The fact is it is slower to use the Object wrappers for primitives than just using the primitives. You're adding the cost of object instantiation, method calls, etc. to things that you use all over the place.

Knuth's "...say about 97% of the time: premature optimization is the root of all evil" quote doesn't really apply here. He was talking about optimisations which make the code (or system) more complicated - if you agree with point #2, this is an optimization which makes the code less complicated!

4. It's the convention:

If you make different stylistic choices to 99% of the other Java programmers out there, there are 2 downsides:

  • You will find other people's code harder to read. 99% of the examples/tutorials/etc out there will use primitives. Whenever you read one you'll have the extra cognitive overhead of thinking about how it would look in the style that you're used to.
  • Other people will find your code harder to read. Whenever you ask questions on Stack Overflow you'll have to sift through answers/comments asking "why aren't you using primitives?". If you don't believe me, just look at the battles people have over things like bracket placement, which doesn't even affect the generated code!

Normally I'd list some counter-points, but I honestly can't think of any good reasons to not go with the convention here!

🌐
javaspring
javaspring.net › blog › java-wrapper-primitive-memory-allocation
Java Wrapper vs Primitive: Memory Allocation Explained (Stack vs Heap in Interviews) — javaspring.net
Understanding their memory allocation (stack vs. heap) and tradeoffs is critical for writing efficient code and acing interviews. Remember: use primitives for speed, wrappers for object functionality!
🌐
Medium
medium.com › @bpnorlander › java-understanding-primitive-types-and-wrapper-objects-a6798fb2afe9
Java: Understanding Primitive Types and Wrapper Objects | by Brian Norlander | Medium
March 19, 2019 - The new primitive type is assigned back to count, which is a wrapper type, so the compiler creates a new Integer object to assign back to the variable count. This loop will create 1000 Integer objects in memory.
🌐
InfoWorld
infoworld.com › home › software development › programming languages › java
A case for keeping primitives in Java | InfoWorld
June 5, 2014 - As shown, the runtime performances of the two versions of the SciMark 2.0 benchmark were consistent with the matrix multiplication results above in that the version with primitives was almost five times faster than the version using wrapper classes. You’ve seen a few variations of Java programs ...