Java Data Types: Primitive and Reference Types Explained

Java data types fall into eight primitive types and reference types such as String, arrays and classes. Compare sizes, ranges and defaults in one table, then see casting, wrapper classes and primitive vs reference behaviour in worked examples.

Java data types

Introduction

Java, as a versatile programming language, provides a rich set of data types to handle various kinds of values. In programming, data types define the kind of values a variable can hold. They guide the computer on how to store and interpret data. Java offers a range of Java data types that cater to different needs, allowing programmers to manage data efficiently.

Diagram of Java data types: primitive types and non-primitive (reference) types
Image source

Java is statically typed: every variable must be declared, with its type, before you can use it (Oracle's Java tutorial). This guide covers the eight primitive types, then reference types, how the two differ, and the conversions you will meet in real code. If you are new to Java, read the basic syntax guide and the guide to Java variables alongside it.

Primitive Data Types: The Building Blocks

A primitive type is predefined by the language and named by a reserved keyword. Primitive values are not objects, and they do not share state with other primitive values. Java has eight. Apart from boolean, whose size is not precisely defined, the size and range of each is fixed by the language:

TypeSizeRangeDefault value
byte8 bits-128 to 1270
short16 bits-32,768 to 32,7670
int32 bits-2,147,483,648 to 2,147,483,6470
long64 bits-9,223,372,036,854,775,808 to 9,223,372,036,854,775,8070L
float32 bits (IEEE 754)magnitude up to about 3.4 × 10380.0f
double64 bits (IEEE 754)magnitude up to about 1.8 × 103080.0d
char16 bits, unsigned'\u0000' to '\uffff' (0 to 65,535)'\u0000'
booleannot precisely definedtrue or falsefalse

Defaults apply to fields and array elements. A local variable has no default: the compiler requires you to assign it before you use it. Sizes, ranges and defaults follow Oracle's Java tutorial and the Java Language Specification.

The eight primitive types in code

One declaration of each, using the examples from this guide:

public class PrimitiveDemo {
    public static void main(String[] args) {
        byte age = 25;
        short population = 15000;
        int numberOfStudents = 500;
        long nationalDebt = 23500000000L;
        float temperature = 98.6f;
        double piValue = 3.141592653589793;
        char grade = 'A';
        boolean isPassed = true;

        System.out.println(age + " " + population + " " + numberOfStudents);
        System.out.println(nationalDebt);
        System.out.println(temperature + " " + piValue);
        System.out.println(grade + " " + isPassed);
    }
}

Output:

25 15000 500
23500000000
98.6 3.141592653589793
A true

Two details catch beginners. A whole-number literal is an int unless it ends in L, so 23500000000L needs the suffix. A floating-point literal such as 98.6 is a double unless it ends in f, so 98.6f needs the suffix. Use single quotes for char and double quotes for String.

Which primitive type should you use?

  • Whole numbers: use int unless you need more range, and long when a value can pass 2,147,483,647. Use byte or short mainly to save memory in large arrays.
  • Decimal numbers: use double. Use float mainly to save memory in large arrays. A float has 24 significant bits (about 7 decimal digits) and a double has 53 (about 15 or 16).
  • Money: never use float or double for precise values such as currency. Oracle's tutorial points to java.math.BigDecimal instead.
  • Single characters: char holds one 16-bit UTF-16 code unit. For text, use String, covered below.
  • Flags: boolean holds true or false.

Two traps: overflow and decimal arithmetic

Integer arithmetic never complains when a result does not fit: the Java Language Specification says the integer operators do not indicate overflow or underflow in any way. Decimal types are binary floating point, so values such as 0.1 and 0.2 are stored approximately.

import java.math.BigDecimal;

public class PrimitiveTraps {
    public static void main(String[] args) {
        int max = 2147483647;               // the largest int
        System.out.println(max);
        System.out.println(max + 1);        // wraps around, no error

        System.out.println(0.1 + 0.2);      // double cannot store 0.1 or 0.2 exactly

        BigDecimal a = new BigDecimal("0.1");
        BigDecimal b = new BigDecimal("0.2");
        System.out.println(a.add(b));       // exact decimal arithmetic
    }
}

Output:

2147483647
-2147483648
0.30000000000000004
0.3

The largest int plus one wraps around to the smallest int, so use long when values can grow. The decimal sum is off in the 17th decimal place, which is why Oracle recommends BigDecimal for currency.

Reference Data Types: Understanding Pointers to Objects

Every type that is not primitive is a reference type. The Java Language Specification names four kinds: class types, interface types, type variables and array types. A variable of a reference type does not hold the object itself. It holds a reference to it, which the specification describes as a pointer to the object, and it can also hold null, the reference that refers to no object.

The JVM specification says objects and arrays are allocated on the heap, which a garbage collector cleans up, while the local variables of a running method sit in that method's stack frame. So in a method, person below is a local variable, and the Person object it refers to is on the heap.

Class types

Any class, whether you write it or it ships with Java, is a reference type. Here is a user-defined class and an object of it:

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Person person = new Person("Alice", 30);

The variable person is a reference to the object that holds the name and age. String is the class type you will use most. String literals such as "abc" are String objects, and String objects are immutable: once created, their values cannot be changed.

Array types

int[] numbers = new int[5];

An array is an object even when its elements are primitive. numbers is a reference to an array of five int elements, and each element starts at the default value 0.

Interface types

An interface lists methods that implementing classes must provide. A variable of an interface type can refer to an object of any class that implements it:

interface Shape {
    void draw();
}

class Circle implements Shape {
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

Shape shape = new Circle();

Here shape has the type Shape and refers to a Circle object.

Collections such as ArrayList and HashMap are classes too, so their variables are reference types. See the HashMap data structure guide for one in use, and the array data structure guide for arrays in depth.

Primitive vs Reference Types in Java: Key Differences

The core difference is what the variable holds. A primitive variable holds the value itself. A reference variable holds a reference to an object, so two variables can end up pointing at the same object.

AspectPrimitive typesReference types
What the variable holdsThe value itselfA reference to an object, or null
Default value (fields)0, 0.0, false or '\u0000'null
Can it be null?NoYes
Assigning one variable to anotherCopies the value; the two variables are independentCopies the reference; both variables point to the same object
Comparing with ==Compares the valuesChecks whether both refer to the same object; use equals() to compare content
Passing to a methodA copy of the value; changes inside the method are lostA copy of the reference; the method can change the object, but not the caller's variable
Where it livesA local variable sits in the method's stack frameThe object or array is allocated on the heap
Memory and speedCompact, with direct access to the valueLess compact, with one extra step through the reference
Typical useSimple values: numbers, characters, true or falseObjects, arrays and custom classes

Primitive vs reference in code

This program shows three of the differences: assignment, == and passing to a method.

public class CopyVsAlias {
    static void changeNumber(int x) { x = 99; }
    static void changeArray(int[] arr) { arr[0] = 99; }

    public static void main(String[] args) {
        int a = 10;
        int b = a;                          // copies the value
        b = 20;
        System.out.println(a + " " + b);

        int[] p = {10, 20};
        int[] q = p;                        // copies the reference: both names point at one array
        q[0] = 99;
        System.out.println(p[0] + " " + q[0]);

        String s1 = new String("java");
        String s2 = new String("java");
        System.out.println(s1 == s2);       // compares references
        System.out.println(s1.equals(s2));  // compares the characters

        int n = 5;
        changeNumber(n);
        System.out.println(n);
        int[] data = {5};
        changeArray(data);
        System.out.println(data[0]);
    }
}

Output:

10 20
99 99
false
true
5
99
  • 10 20: copying an int copies the value, so changing b leaves a alone.
  • 99 99: copying an array variable copies the reference, so p and q see the same array.
  • false then true: each new String(...) creates a separate String object, so == is false. equals() compares the characters, so it is true.
  • 5 then 99: a method receives a copy of the value, or a copy of the reference. It can change an array's contents through that reference, but it cannot change which array the caller's variable points to. Oracle's tutorial describes both cases as passing by value.

Wrapper Classes and Autoboxing

Each primitive type has a matching wrapper class, which holds the value inside an object: boolean and Boolean, byte and Byte, char and Character, float and Float, int and Integer, long and Long, short and Short, double and Double.

Autoboxing is the automatic conversion the compiler makes between a primitive and its wrapper class. Unboxing is the reverse. It is how a List<Integer> works: the list holds Integer objects, and the compiler boxes and unboxes the values for you.

List<Integer> scores = new ArrayList<>();
scores.add(95);                 // the int 95 is boxed into an Integer object
int first = scores.get(0);      // unboxed back to an int

Compare wrapper objects with equals(), not ==. The language guarantees that boxing the same constant between -128 and 127 gives the same object each time, so == happens to work there. For other values it allows but does not require sharing, so == can be false.

public class WrapperDemo {
    public static void main(String[] args) {
        Integer a = 127;
        Integer b = 127;
        System.out.println(a == b);         // true: the language guarantees it for -128 to 127
        System.out.println(a.equals(b));    // true
    }
}

Output:

true
true

Type Casting Between Java Data Types

Java converts between numeric types in two directions. A widening conversion goes to a type that can hold more, such as int to long or float to double, and Java applies it automatically. A narrowing conversion goes the other way, such as double to int or int to byte. It may lose information about magnitude or precision, so you write a cast yourself. The one exception is a constant that fits, which is why byte age = 25; compiles without a cast.

Two rules from the Java Language Specification explain the output below. Narrowing an integer keeps only the lowest bits, which can change the sign. Narrowing a floating-point value to an integer rounds toward zero. Even some widening conversions (int or long to float, and long to double) can lose precision.

public class CastingDemo {
    public static void main(String[] args) {
        int i = 130;
        byte b = (byte) i;          // narrowing: only the low 8 bits survive
        double d = 9.99;
        int whole = (int) d;        // the fraction is cut off, not rounded
        long big = i;               // widening: automatic, nothing is lost
        char c = 'A';
        int code = c + 1;           // char is widened to int before the addition
        System.out.println(b + " " + whole + " " + big + " " + code + " " + (char) code);
    }
}

Output:

-126 9 130 66 B

130 does not fit in a byte (the maximum is 127), so only its low 8 bits are kept and the value becomes -126. 9.99 becomes 9, not 10. The char 'A' is widened to an int before 1 is added, giving 66, and casting 66 back to char gives 'B'.

Choosing Between Primitive and Reference Types

Primitive Types:

•    Ideal for simple values such as numbers or characters.

•    Lightweight and memory-efficient due to direct value storage.

•    Faster access speed as no memory address indirection is involved.

Reference Types:

•    Essential for managing complex data structures and objects.

•    Used when data needs to encapsulate multiple data pieces and behaviors.

•    Slightly less memory-efficient due to storing references.

•    Access involves a slight delay due to referencing but enables sharing data across program sections.

Wrapping Up

  • Java has two kinds of types: eight primitives that hold values directly, and reference types that point to objects.
  • Use int for whole numbers, long when values can pass 2,147,483,647, double for decimals and BigDecimal for money.
  • Compare primitives with ==. Compare objects such as String with equals().
  • Widening conversions are automatic. Narrowing conversions need a cast and can lose data.

To run the examples yourself, follow the guide to setting up your Java environment. To see how the JVM treats the stack and heap mentioned above, read about JVM architecture.

FAQs: Java Data Types

What are the data types in Java?

Java has two groups of data types. The eight primitive types are byte, short, int, long, float, double, char and boolean. Reference types are everything else: classes (including String), interfaces and arrays. The Java Language Specification also lists type variables as a fourth kind of reference type.

What are the 8 primitive data types in Java?

They are byte (8 bits), short (16), int (32), long (64), float (32), double (64), char (16) and boolean. The first four hold whole numbers, float and double hold decimals, char holds one UTF-16 code unit, and boolean holds true or false. The table above gives each range and default.

What is the difference between primitive and reference data types in Java?

A primitive variable holds its value directly. A reference variable holds a reference to an object, or null. Primitives have fixed sizes, are not objects and default to 0 or false, while references default to null. Assigning a reference copies the reference, so two variables can share one object.

Is String a primitive data type in Java?

No. String is a class, so it is a reference type, but the language gives it special support. String literals such as "abc" are String objects, and String objects are immutable. Oracle's tutorial notes you may tend to think of it as primitive, though technically it is not.

Can I use primitive data types to store decimal numbers?

Yes. float and double store decimals, and double is generally the default choice. Both are approximate, so Oracle says they should never be used for precise values such as currency. Use java.math.BigDecimal for money instead.

What is the default value of each Java data type?

For fields and array elements: 0 for byte, short and int, 0L for long, 0.0f for float, 0.0d for double, '\u0000' for char, false for boolean and null for every reference type. Local variables have no default and must be assigned before use, or the code does not compile.

×

Our Courses

Practice-Based Learning Tracks, Supercharged By A.I.