When to Use Wrapper Classes and Primitive Types

This is a compilation of several sources, but prompted by the StackOverflow Question: "When should I go for wrapper class over primitive types?"

____________

The 8 Primitive Types built into Java:

Primitive	Wrapper Class
boolean	:	Boolean
byte	:	Byte
char	:	Character
int	:	Integer
float	:	Float
double	:	Double
long	:	Long
short	:	Short

Default values for Primitive Types:

Data Type	Default Value (for fields)
byte	0
short	0
int	0
long	0L
float	0.0f
double	0.0d
char	'\u0000'
String (or any object)  null
boolean	false

"Generally, you should use primitive types unless you need an object for some reason (e.g. to put in a collection)."

"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."

___________

Interesting read from an IBM Research Center in 1998: Primitive Types Considered Harmful.

___________

Java Wrapper Classes from w3resource:

Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper classes, because they "wrap" the primitive data type into an object of that class. The wrapper classes are part of the java.lang package, which is imported by default into all Java programs.

The wrapper classes in java servers two primary purposes.

  • To provide mechanism to ‘wrap’ primitive values in an object so that primitives can do activities reserved for the objects like being added to ArrayList, Hashset, HashMap etc. collection.
  • To provide an assortment of utility functions for primitives like converting primitive types to and from string objects, converting to various bases like binary, octal or hexadecimal, or comparing various objects.

___________

Good StackOverflow answer from book "Effective Java" comparing performance of Long vs. long in an iteration where long is 6.8 seconds, Long is 43 seconds.

Posted April 05, 2017 05:08 PM EDT

More Like This Post