HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

5) Generics Lesson

Java Generics and Primitive Types

4 min to complete · By Ryan Desmond

When using generics in Java, primitive data types are not allowed. To work around this, and for many other helpful reasons, Java has what are known as "wrapper types". These are object-types that "wrap" primitive types.

What is a Wrapper Class in Java

By now, you have seen that in addition to int, double, float, long and so on, you also have Integer, Double, Float, Long and so on. For each primitive data type in Java, you also have what is known as a "wrapper type". These are just object types that "wrap" Java's primitive data types into a Java class and add functionality. For instance:

int i = Integer.parseInt("7");

In the example above, you're using the parseInt() helper method in the Integer wrapper class to convert a String "7" into an int 7. This is the helpful type of functionality add by wrapper classes.

Primitive Data Type and Their Wrapper Class

Below is a table showing all the primitive types and their respective wrapper class.

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

Alert: It is not possible to instantiate a generic class/object (or call a generic method) using a primitive type. Generics only work with Object Types.

//this will NOT work
ArrayList<int> badList = new ArrayList();

// this WILL work
ArrayList<Integer> goodList = new ArrayList();

Why Have a Wrapper Class?

When you just need a simple primitive data type, just use the simple primitive data type. That said, there are often circumstances where you need the added functionality/methods that these wrapper types offer.

Explicit Type Conversion

You can convert a String to int using the Integer wrapper type.

String intStr = "123";
int x = Integer.parseInt(intStr);
//or
String doubleStr = "123.45";
double y = Double.parseDouble(doubleStr)
//or
String floatStr = "123.4f";
float f = Float.parseFloat(floatStr)
// and so on

Implicit Type Conversion

You can convert a primitive type to its wrapper type (and vice versa) implicitly.

// these all work
Integer i = new Integer(12);
int val = i;
Integer x = val;

Summary: Java Generics and Java Primitive Types

  • Generics work only with object data types
  • You cannot use primitive data types with generics
  • int is a primitive data type, and Integer is its wrapper
  • Primitive wrapper classes offer additional functionality
  • You can explicitly and implicitly convert from the wrapper type to the primitive type