106

When I should go for wrapper class over primitive types? Or On what circumstance I should choose between wrapper / Primitive types?

Gopi
  • 5,012
  • 18
  • 62
  • 127
  • 2
    http://www.w3resource.com/java-tutorial/java-wrapper-classes.php This article would helpful for this discussion. – pankaj Oct 24 '14 at 08:55

11 Answers11

71

Others have mentioned that certain constructs such as Collections require objects and that objects have more overhead than their primitive counterparts (memory & boxing).

Another consideration is:

It can be handy to initialize Objects to null or send null parameters into a method/constructor to indicate state or function. This can't be done with primitives.

Many programmers initialize numbers to 0 (default) or -1 to signify this, but depending on the scenario, this may be incorrect or misleading.

This will also set the scene for a NullPointerException when something is being used incorrectly, which is much more programmer-friendly than some arbitrary bug down the line.

VPK
  • 2,896
  • 1
  • 23
  • 34
pstanton
  • 29,804
  • 23
  • 108
  • 165
  • 16
    "It can be handy to initialise Objects to null". It cannot be handy because this is incorrect, if the field is optional you should indicate this explicitly. – Eddie Jamsession Jan 22 '15 at 09:02
  • 9
    lol @EddieJamsession thanks, i will never initialise to null again. (pfffft) – pstanton Feb 01 '15 at 23:49
  • 1
    @EddieJamsession If initialising Objects to null as a way to indicate failure when setting the actual value has failed, how else would you propose to catch this problem? Oh, I just realised as I type this: exceptions. A NullPointerException is too generic; it'd be better to use very specific custom exceptions to indicate what has gone wrong. Good, I'll be doing that from now on... – klaar Nov 16 '17 at 08:46
  • 1
    @EddieJamsession After reading up on the matter, I've run into the concept of an Optional object. Right. – klaar Nov 16 '17 at 09:59
  • @klaar what’s an optional object? – carloswm85 Sep 28 '20 at 21:47
  • @carloswm85 A java.util.Optional object is a a wrapper around an object that is able to discern between the presence and absence of a value or object. It is designed so that you do not have to have use a certain real value as a placeholder for the absence of a value. The value NULL is used quite commonly as such a placeholder, but it doesn't force you to take into account the exceptional case (resulting in NullPointerExceptions when you're being sloppy), while an Optional does because you have to think about what you want to do when the wrapper is empty. – klaar Oct 12 '20 at 13:35
20

Generally, you should use primitive types unless you need an object for some reason (e.g. to put in a collection). Even then, consider a different approach that doesn't require a object if you want to maximize numeric performance. This is advised by the documentation, and this article demonstrates how auto-boxing can cause a large performance difference.

Matthew Flaschen
  • 255,933
  • 45
  • 489
  • 528
  • 3
    the performance hit is not so great that code legibility/reliability should take a back seat. – pstanton Oct 15 '09 at 05:39
  • 3
    First, using primitives appropriately will not make your code illegible. Second, the performance hit is significant in some cases. It's absurd to say it never is. – Matthew Flaschen Oct 15 '09 at 06:00
  • 1
    @pstanton: please explain how `Integer` is more legible than `int`. – Stephen C Oct 15 '09 at 07:29
  • In many cases Integer is no more legible than int and in these cases I will always use int, or if I know a certain variable will NEVER be null, i'll use int because int is as you've pointed out slightly more efficient. However, in many cases it is easier for another programmer to understand the state of a variable when an object is used, as it can be initialised to null to signify that it is not ready. For example if you have an unsaved database record which has a unique incrementing numeric id, should this id be 0, -1 or null before it is assigned a valid id? In that case Objects are better. – pstanton Oct 15 '09 at 08:37
  • regarding performance - in special cases, the performance hit can be significant, ie if you are creating a multitude of these Objects very rapidly or if many many many of them build up over a period of time. However, i'd expect a decent programmer to be able to identify these special cases either avoid or amend accordingly. I never said that it's NEVER significant, however generally speaking, it isn't. – pstanton Oct 15 '09 at 08:41
  • Performance takes the first seat based on the nature of the application. Generally speaking, if its a web-app then millisecs wont be significant but it is a desktop app it makes sense not to take that extra sec directly off the face of the user. – Pradeep Apr 21 '11 at 02:47
  • Here's a video from a Google Usergroup Meeting where this specific float vs Float topic is covered in the context of Android's animation framework, mostly regarding Garbage Collection issues https://youtu.be/wJYTBjMZJh0?t=11m20s This is presented by the guy working at Google on the animation framework (Chet Haase) – Daniel F Mar 22 '15 at 14:38
  • absolutely animation is an example of where you would strictly use primitives because variables constantly change in high frequency. again, i would expect a decent programmer to identify this case. – pstanton Apr 26 '15 at 23:35
15

In my opinion, if my class members are wrapper variables, it does not rely on default values, which is developer friendly behavior.

1.

class Person {
   int SSN ; // gets initialized to zero by default 
}

2.

class PersonBetter {
  Integer SSN; //gets initialized to null by default
}

In the first case, you cannot keep SSN value uninitialized. It may hurt if you are not checking if the value was set before you attempt to use it.

In the second case, you can keep SSN initialized with null. Which can lead to NullPointerException but it is better than unknowingly inserting default values(zero) as SSN into to the database whenever you attempt to use it without initializing SSN field.

Cody
  • 304
  • 4
  • 8
  • 3
    The builder pattern is meant to get around this. In this scenario, you make a `PersonBuilder` that throws an exception if SSN isn't set prior to calling "build" to get the `Person` instance. I think this sort of thing is excessive, but it's what the Java language promotes for proper patterns. – Sandy Chapman Feb 29 '16 at 12:13
9

I would only use the wrapper types if you have to.

In using them you don't gain much, besides the fact that they are Objects.

And, you lose overhead in memory usage and time spent boxing/unboxing.

jjnguy
  • 128,890
  • 51
  • 289
  • 321
  • 4
    you might not gain much, but you don't lose much either. unless you're running on a 1990's palm pilot. – pstanton Oct 15 '09 at 05:43
  • The fact that they are Objects also give them much more context and encapsulation than as a plain primitive. So you may actually gain much depending on what those primitives are meant for and where they're being used. – aberrant80 Oct 15 '09 at 06:34
4

Practically I had encountered a situation where use of wrapper class can be explained.

I created a service class which had a long type variable

  1. If the variable is of type long - when not initialized, it will be set to 0 - this will be confusing to the user when displayed in GUI
  2. If the variable is of type Long - when not initialized, it will be set to null - this null value won't show up in GUI.

This applies to Boolean as well where values can be more confusing when we use primitive boolean(as default value is false).

danopz
  • 2,999
  • 5
  • 26
  • 36
3

Collections are the typical case for the simple Java wrapper objects. However, you might consider giving the Wrapper a more specific meaning in the code (value object).

IMHO there's almost always a benefit to use value objects when it boils down to readability and maintainance of the code. Wrapping simple data structures inside of objects when they have certain responsibilities often simplifies the code. This is something that is very important in Domain-Driven Design.

There is of course the performance issue, but I tend to ignore that until I have the possibility to measure the performance with proper data and do more directed actions towards the problematic area. It might also be easier to understand the performance issue if the code is easy to understand as well.

3

performance of applications that are dominated by numerical calculations can benefit greatly from the use of primitives.

primitive types, one uses the == operator, but for wrapper the preferred choice is to call the equals() method.

"Primitive types considered harmful" because they mix "procedural semantics into an otherwise uniform object-oriented model.

Many programmers initialize numbers to 0 (default) or -1 to signify this, but depending on the scenario, this may be incorrect or misleading.

loknath
  • 1,322
  • 15
  • 24
1

If you want to use Collections, you must use Wrapper classes.

Primitive types, are used for arrays. Also, to represent data that has no behaviour,for example, a counter, or a boolean condition.

Since autoboxing, the "when to use primitive or wrapper" frontier has become quite fuzzy.

But remember, Wrappers are objects, so you get all the fancy Java features. For example, you can use reflexion to create Integer objects, but not int values. Wrapper classes also have methods such as valueOf.

Tom
  • 39,851
  • 25
  • 129
  • 164
  • Other than collections, i shouldn't use wrapper classes? How about using it for ordinary declaration like Integer i = new Integer(10); Is it good to do like this? – Gopi Oct 15 '09 at 05:23
  • autoboxing allows you to do Integer i = 10; – Tom Oct 15 '09 at 05:25
  • 1
    No, Sri. If you don't have a requirement that i be an object, don't make it one. – Matthew Flaschen Oct 15 '09 at 05:30
  • Autoboxing will unbox the above declared i to int i=10 or Integer i = 10? – Gopi Oct 15 '09 at 05:30
  • 3
    int pi = new Integer(10); works. Integer oi = 10; works. int ni = null; doesn't work. the LHS is converted to whatever the RHS requires. – pstanton Oct 15 '09 at 05:47
0

If you want to create a value type. Something like a ProductSKU or AirportCode.

When a primitive type (string in my examples) defines equality, you'll want to override equality.

Chris Missal
  • 5,516
  • 2
  • 25
  • 45
  • 2
    there are still good reasons to wrap a value type that contains a string as the base object. – Chris Missal Oct 15 '09 at 05:36
  • your answer just doesn't make sense. i'm not sure what you're saying. i agree with your comment though, wrapper classes are a good idea if they improve legibility. – pstanton Oct 15 '09 at 05:41
  • Value types or value objects should be created and be immutable. For instance, it wouldn't make sense to create a "CountryCode" object like: new CountryCode("USA") then create another object the same way, where later they are different. They're just strings to start with, but they have meaning behind them. By using strings, you're able to modify them (by appending more data, etc) but they would no longer be equal. See this article for a better description of what I'm trying to explain :) I hope this makes sense http://c2.com/cgi/wiki?ValueObject – Chris Missal Oct 15 '09 at 06:06
0

Primitive values in Java are not object. In order to manipulate these values as object the java.lang package provides a wrapper class for each of the primitive data type.

All Wrapper classes are final. The object of all wrapper classes that can be initiated are immutable that means the value in the wrapper object can not be changed.

Although, the void class is considered a wrapper class but it does not wrap any primitive values and is not initiable. It does not have public constructor, it just denotes a class object representing the keyword void.

Community
  • 1
  • 1
Ahmad Sayeed
  • 194
  • 1
  • 9
0

When to Use Primitive Types

  • When doing a large amount of calculations, primitive types are always faster — they have much less overhead.
  • When you don’t want the variable to be able to be null.
  • When you don’t want the default value to be null.
  • If the method must return a value

When to Use Wrapper Class

  • When you are using Collections or Generics — it is required
  • If you want the MIN_SIZE or MAX_SIZE of a type.
  • When you want the variable to be able to be null.
  • When you want to default value to be null.
  • If sometimes the method can return a null value.

from https://medium.com/@bpnorlander/java-understanding-primitive-types-and-wrapper-objects-a6798fb2afe9

Feuda
  • 1,855
  • 22
  • 24