Java Data Types

Every value in Java is either one of eight primitive types or a reference to an object. The primitive types are fixed-size numbers, characters and booleans that behave like the hardware they run on: integers wrap around when they overflow and floating-point numbers are binary approximations. This page shows each type's range, how to write literals, the arithmetic rules that surprise people, conversions between types, and what a reference really is.

Contents

Primitive types and reference types

Java has two kinds of types, and the difference explains a lot of its behavior:

  • Primitive types hold a value directly: a variable of type int is 32 bits containing the number itself. There are exactly eight of them, and their sizes are the same on every platform, which was a deliberate change from C, where int could be 16 or 32 bits depending on the machine.
  • Reference types are everything else: classes, interfaces, arrays, enums and records. A variable of type String or List holds a reference, which points to an object stored on the heap. Several variables can refer to the same object, and a reference can be null.
The eight primitive types
TypeSizeHoldsDefaultTypical use
byte8 bitsWhole numbers -128 to 1270Raw binary data, files, network
short16 bits-32,768 to 32,7670Rare; large arrays where memory matters
int32 bitsAbout ±2.1 billion0The default for whole numbers
long64 bitsAbout ±9.2 × 10180Timestamps, IDs, large counts
float32 bitsAbout 7 significant decimal digits0.0Graphics, large arrays of measurements
double64 bitsAbout 15 to 17 significant digits0.0The default for fractional numbers
char16 bitsOne UTF-16 code unit, 0 to 65,535'\u0000'Characters of text
booleanNot specifiedtrue or falsefalseConditions and flags

The defaults apply to fields and array elements. Local variables have no default: the compiler refuses to read one before it is assigned.

Ranges of the numeric types

Each wrapper class (Integer, Long and so on) has constants for its type's size and limits. The program prints them as a table, then a few literals.

Java
public class Primitives {

    static void row(String type, Object bits, Object min, Object max) {
        System.out.printf("%-7s %4s %22s %22s%n", type, bits, min, max);
    }

    public static void main(String[] args) {
        row("type", "bits", "min", "max");
        row("byte", Byte.SIZE, Byte.MIN_VALUE, Byte.MAX_VALUE);
        row("short", Short.SIZE, Short.MIN_VALUE, Short.MAX_VALUE);
        row("int", Integer.SIZE, Integer.MIN_VALUE, Integer.MAX_VALUE);
        row("long", Long.SIZE, Long.MIN_VALUE, Long.MAX_VALUE);
        row("char", Character.SIZE, (int) Character.MIN_VALUE, (int) Character.MAX_VALUE);
        row("float", Float.SIZE, Float.MIN_VALUE, Float.MAX_VALUE);
        row("double", Double.SIZE, Double.MIN_VALUE, Double.MAX_VALUE);
        System.out.println("boolean: true or false; its size in memory is not specified");

        // Literals
        long big = 9_000_000_000L;   // L: without it, the literal is an int and too large
        float f = 1.5f;              // f: without it, 1.5 is a double
        int hex = 0xFF;
        int bin = 0b1010;
        char c = 'A';
        System.out.println(big + " " + f + " " + hex + " " + bin + " " + c + " " + (int) c);
    }
}

Output:

Output
type    bits                    min                    max
byte       8                   -128                    127
short     16                 -32768                  32767
int       32            -2147483648             2147483647
long      64   -9223372036854775808    9223372036854775807
char      16                      0                  65535
float     32                1.4E-45           3.4028235E38
double    64               4.9E-324 1.7976931348623157E308
boolean: true or false; its size in memory is not specified
9000000000 1.5 255 10 A 65
  • The integer types are signed two's complement, so each has one more negative value than positive: byte runs from -128 to 127.
  • char is the only unsigned type, 0 to 65,535. It is a number underneath, which is why (int) 'A' is 65.
  • For float and double, MIN_VALUE is the smallest positive value, not the most negative one. The most negative double is -Double.MAX_VALUE. This naming catches many people writing "find the maximum" loops that start from Double.MIN_VALUE.
  • The size of a boolean is not defined by the language. In practice a boolean field or array element takes one byte in HotSpot.

Writing literals

A literal is a value written directly in source code. Its form decides its type: 5 is an int, 5L a long, 5.0 a double and 5.0f a float. The program uses every common form, including one that looks harmless but is not.

Java
public class Literals {

    public static void main(String[] args) {
        int million = 1_000_000;               // underscores are only for readability
        int hex = 0xFF;                        // 0x: base 16
        int binary = 0b1010_1010;              // 0b: base 2 (Java 7+)
        int octal = 010;                       // a leading 0 means base 8!
        long big = 9_000_000_000L;             // L: the literal is a long
        float f = 1.5f;                        // f: the literal is a float, not a double
        double sci = 6.022e23;                 // scientific notation
        char letter = 'A';
        char euro = '€';                  // a Unicode escape
        char tab = '\t';

        System.out.println("million " + million + ", hex " + hex + ", binary " + binary);
        System.out.println("octal 010 = " + octal);
        System.out.println("big " + big + ", float " + f + ", sci " + sci);
        System.out.println("letter " + letter + " has code " + (int) letter);
        System.out.println("'A' + 1 = " + (letter + 1) + ", (char) ('A' + 1) = "
                + (char) (letter + 1));
        System.out.println("euro sign code point: " + (int) euro + ", tab code: " + (int) tab);
    }
}

Output:

Output
million 1000000, hex 255, binary 170
octal 010 = 8
big 9000000000, float 1.5, sci 6.022E23
letter A has code 65
'A' + 1 = 66, (char) ('A' + 1) = B
euro sign code point: 8364, tab code: 9
  • Underscores (Java 7 and later) can go between digits for readability: 1_000_000.
  • 0xFF is hexadecimal 255 and 0b1010_1010 is binary 170.
  • A leading zero makes a number octal: 010 is 8, not 10. Zero-padding a number for alignment, such as int month = 08;, changes its value, and 08 does not even compile because 8 is not an octal digit.
  • Without the L, 9_000_000_000 would not compile: the literal is an int and too large. Without the f, 1.5 is a double and cannot be assigned to a float without a cast.
  • Characters are numbers: 'A' + 1 is the int 66, and casting back gives 'B'. '€' is the euro sign, code 8,364.

Integer arithmetic: overflow and division

Integer arithmetic in Java is fast because it maps directly onto CPU instructions, and it behaves like them too. The program shows the cases that cause bugs: overflow, a multiplication that overflows before it is stored, division and remainder of negative numbers, and division by zero.

Java
public class IntegerMath {

    public static void main(String[] args) {
        // Overflow wraps around silently
        int max = Integer.MAX_VALUE;
        System.out.println("Integer.MAX_VALUE + 1 = " + (max + 1));
        try {
            Math.addExact(max, 1);
        } catch (ArithmeticException e) {
            System.out.println("Math.addExact(MAX, 1): " + e.getMessage());
        }

        // int * int overflows BEFORE the result is stored in a long
        long wrong = 1_000_000 * 1_000_000;
        long right = 1_000_000L * 1_000_000;
        System.out.println("1_000_000 * 1_000_000 into a long:  " + wrong);
        System.out.println("1_000_000L * 1_000_000 into a long: " + right);

        // Integer division truncates toward zero
        System.out.println("7 / 2 = " + 7 / 2 + ", -7 / 2 = " + -7 / 2);
        System.out.println("7 % 3 = " + 7 % 3 + ", -7 % 3 = " + -7 % 3);
        System.out.println("Math.floorDiv(-7, 2) = " + Math.floorDiv(-7, 2)
                + ", Math.floorMod(-7, 3) = " + Math.floorMod(-7, 3));

        // Division by zero is an error for integers
        try {
            int zero = 0;
            System.out.println(1 / zero);
        } catch (ArithmeticException e) {
            System.out.println("1 / 0: ArithmeticException: " + e.getMessage());
        }

        // Math.abs cannot represent the absolute value of MIN_VALUE
        System.out.println("Math.abs(Integer.MIN_VALUE) = " + Math.abs(Integer.MIN_VALUE));
    }
}

Output:

Output
Integer.MAX_VALUE + 1 = -2147483648
Math.addExact(MAX, 1): integer overflow
1_000_000 * 1_000_000 into a long:  -727379968
1_000_000L * 1_000_000 into a long: 1000000000000
7 / 2 = 3, -7 / 2 = -3
7 % 3 = 1, -7 % 3 = -1
Math.floorDiv(-7, 2) = -4, Math.floorMod(-7, 3) = 2
1 / 0: ArithmeticException: / by zero
Math.abs(Integer.MIN_VALUE) = -2147483648
  • Integer.MAX_VALUE + 1 wraps around to Integer.MIN_VALUE with no error. Math.addExact, subtractExact, multiplyExact and toIntExact throw ArithmeticException instead, which turns a silent wrong result into a visible one.
  • long wrong = 1_000_000 * 1_000_000 gives -727,379,968 even though a long could hold a trillion. Both operands are int, so the multiplication happens in 32 bits and overflows; only the wrong result is widened to long. Making one operand a long (1_000_000L) makes the whole multiplication 64-bit.
  • Integer division truncates toward zero: 7 / 2 is 3 and -7 / 2 is -3. The remainder takes the sign of the left operand, so -7 % 3 is -1. That breaks code such as index % size for negative indexes; Math.floorMod(-7, 3) gives 2, and Math.floorDiv rounds toward negative infinity.
  • Integer division by zero throws ArithmeticException. Floating-point division by zero does not, as the next section shows.
  • Math.abs(Integer.MIN_VALUE) is still negative, because +2,147,483,648 does not fit in an int. Code that computes Math.abs(hashCode()) % n can therefore produce a negative index.

Floating point: why 0.1 + 0.2 is not 0.3

float and double follow the IEEE 754 standard: a sign, an exponent and a binary fraction (23 bits for float, 52 for double). That gives a huge range, but only fractions whose denominator is a power of two are exact. The program shows the rounding, where precision runs out, the special values, and how to compare.

Java
import java.math.BigDecimal;

public class FloatingPoint {

    public static void main(String[] args) {
        // Most decimal fractions are not exact in binary
        System.out.println("0.1 + 0.2 = " + (0.1 + 0.2));
        System.out.println("0.1 really is " + new BigDecimal(0.1));
        System.out.println("0.1f + 0.2f = " + (0.1f + 0.2f)
                + " (the float nearest 0.3, not exactly 0.3)");

        // Precision runs out for big numbers
        System.out.println("(float) 16_777_217 = " + (float) 16_777_217);
        System.out.println("1e16 + 1 == 1e16: " + (1e16 + 1 == 1e16));
        System.out.println("gap between doubles near 1e16: " + Math.ulp(1e16));
        System.out.println("gap between doubles near 1.0:  " + Math.ulp(1.0));

        // Special values instead of exceptions
        System.out.println("1.0 / 0 = " + 1.0 / 0 + ", -1.0 / 0 = " + -1.0 / 0
                + ", 0.0 / 0 = " + 0.0 / 0);
        double nan = Double.NaN;
        System.out.println("NaN == NaN: " + (nan == nan) + ", Double.isNaN: " + Double.isNaN(nan));
        System.out.println("0.0 == -0.0: " + (0.0 == -0.0)
                + ", Double.valueOf(0.0).equals(-0.0): " + Double.valueOf(0.0).equals(-0.0));

        // Compare with a tolerance, not ==
        double a = 0.1 + 0.2;
        System.out.println("a == 0.3: " + (a == 0.3)
                + ", Math.abs(a - 0.3) < 1e-9: " + (Math.abs(a - 0.3) < 1e-9));
    }
}

Output:

Output
0.1 + 0.2 = 0.30000000000000004
0.1 really is 0.1000000000000000055511151231257827021181583404541015625
0.1f + 0.2f = 0.3 (the float nearest 0.3, not exactly 0.3)
(float) 16_777_217 = 1.6777216E7
1e16 + 1 == 1e16: true
gap between doubles near 1e16: 2.0
gap between doubles near 1.0:  2.220446049250313E-16
1.0 / 0 = Infinity, -1.0 / 0 = -Infinity, 0.0 / 0 = NaN
NaN == NaN: false, Double.isNaN: true
0.0 == -0.0: true, Double.valueOf(0.0).equals(-0.0): false
a == 0.3: false, Math.abs(a - 0.3) < 1e-9: true
  • 0.1 is stored as the nearest double, which is slightly more than 0.1, and so is 0.2; their sum rounds to 0.30000000000000004, which is a different double from the one nearest 0.3.
  • The float sum prints 0.3 because it happens to round to the float nearest 0.3, and printing shows the shortest text that identifies that float. It is still not exactly 0.3; float is less precise, not more.
  • A float has 24 bits of precision, so 16,777,217 (224 + 1) cannot be stored and becomes 16,777,216. A double runs out at 253: near 1016 neighbouring doubles are 2.0 apart, so adding 1 changes nothing. Math.ulp gives this gap.
  • Floating-point division by zero gives Infinity or -Infinity, and 0.0 / 0 gives NaN (not a number). NaN is not equal to anything, itself included, so test with Double.isNaN.
  • 0.0 == -0.0 is true, but Double.equals treats them as different, as it does with NaN (where equals returns true). This matters for map keys and for sorting.
  • Compare computed doubles with a tolerance suited to the problem, not with ==. For money, use BigDecimal or whole cents in a long.

Converting between types: widening, narrowing and promotion

Java converts automatically when no information about the magnitude can be lost (widening, such as int to long), and requires a cast when it can (narrowing, such as double to int). The program shows what each kind of conversion really does to the value, including two cases where an automatic conversion still loses precision.

Java
public class Conversions {

    public static void main(String[] args) {
        // Widening happens automatically and never loses the magnitude
        int i = 1_234_567_890;
        long asLong = i;
        float asFloat = i;                     // allowed, but float has only 24 bits of precision
        System.out.println("int " + i + " -> long " + asLong + " -> float " + (long) asFloat);

        // Narrowing needs a cast and keeps only the low bits or the whole part
        System.out.println("(byte) 200 = " + (byte) 200);
        System.out.println("(int) 3.99 = " + (int) 3.99 + ", (int) -3.99 = " + (int) -3.99);
        System.out.println("(int) 1e20 = " + (int) 1e20 + " (clamped to Integer.MAX_VALUE)");
        System.out.println("(int) Double.NaN = " + (int) Double.NaN);
        System.out.println("Math.round(2.5) = " + Math.round(2.5)
                + ", Math.round(-2.5) = " + Math.round(-2.5));

        // byte, short and char arithmetic is done in int
        byte x = 10;
        byte y = 20;
        int sum = x + y;                       // byte z = x + y; does not compile
        x += y;                                // compound assignment casts back to byte
        System.out.println("x + y = " + sum + "; x += y gives " + x);
        byte b = 120;
        b += 10;                               // the hidden cast also hides overflow
        System.out.println("byte 120 += 10 gives " + b);

        // Mixed expressions use the widest type
        System.out.println("5 / 2 = " + 5 / 2 + ", 5 / 2.0 = " + 5 / 2.0
                + ", 'a' + 1 = " + ('a' + 1) + ", \"" + "a" + "\" + 1 = " + ("a" + 1));
    }
}

Output:

Output
int 1234567890 -> long 1234567890 -> float 1234567936
(byte) 200 = -56
(int) 3.99 = 3, (int) -3.99 = -3
(int) 1e20 = 2147483647 (clamped to Integer.MAX_VALUE)
(int) Double.NaN = 0
Math.round(2.5) = 3, Math.round(-2.5) = -2
x + y = 30; x += y gives 30
byte 120 += 10 gives -126
5 / 2 = 2, 5 / 2.0 = 2.5, 'a' + 1 = 98, "a" + 1 = a1
  • Widening int to float is automatic, yet 1,234,567,890 became 1,234,567,936: a float keeps the magnitude but only about 7 significant digits. The same happens from long to double above 253.
  • Narrowing between integer types keeps only the low bits: 200 is 11001000 in binary, which as a signed byte is -56.
  • Casting a floating-point number to an integer drops the fraction (toward zero, so -3.99 becomes -3). Values out of range are clamped to the minimum or maximum, and NaN becomes 0. Use Math.round, floor or ceil when you want rounding; Math.round rounds halves up, so -2.5 becomes -2.
  • Arithmetic on byte, short and char is done in int, so byte z = x + y does not compile. Compound assignment such as x += y contains a hidden cast back to byte, which is why it compiles, and also why 120 + 10 silently became -126.
  • In a mixed expression, the narrower operand is promoted to the wider type: 5 / 2.0 is a double division. With a String, + means concatenation, so "a" + 1 is "a1" while 'a' + 1 is 98.
Conversion rules
FromToAutomatic?What can go wrong
byte, short, charintYesNothing
intlong, doubleYesNothing
int, longfloat; long to doubleYesLost precision for large values
A wider integerA narrower integerCast neededHigh bits dropped; sign can flip
double, floatAny integer typeCast neededFraction dropped; out-of-range values clamped
doublefloatCast neededPrecision lost; large values become Infinity

References: what a variable of an object type holds

A reference variable holds the location of an object, not the object. Java always passes arguments by value, but for an object the value passed is the reference. The program passes an int and a list to a method that changes both, then shows two references to one array and the default values of fields.

Java
import java.util.ArrayList;
import java.util.List;

public class References {

    static void change(int n, List<String> list) {
        n = 99;                      // changes the local copy only
        list.add("added");           // changes the object both references point to
    }

    public static void main(String[] args) {
        int number = 1;
        List<String> items = new ArrayList<>();
        change(number, items);
        System.out.println("number: " + number + ", items: " + items);

        // Two references, one object
        int[] a = {1, 2, 3};
        int[] b = a;
        b[0] = 100;
        System.out.println("a[0] after b[0] = 100: " + a[0]);

        // Default values for fields (locals have none and must be assigned)
        Defaults d = new Defaults();
        System.out.println("int " + d.i + ", double " + d.d + ", boolean " + d.b);
        System.out.println("char code " + (int) d.c + ", String " + d.s);
    }

    static class Defaults {
        int i;
        double d;
        boolean b;
        char c;
        String s;
    }
}

Output:

Output
number: 1, items: [added]
a[0] after b[0] = 100: 100
int 0, double 0.0, boolean false
char code 0, String null
  • Setting n = 99 inside the method changed the method's own copy of the number, so number is still 1.
  • list.add("added") changed the one list that both the caller and the method refer to. Had the method assigned list = new ArrayList<>(), the caller would not have seen it: only the copy of the reference would have changed. That is the difference between "pass by value" and "pass by reference".
  • b = a copied the reference, so b[0] = 100 changed the array a refers to. See arrays for how to make real copies.
  • Fields get default values (0, 0.0, false, the zero char, null); a field of a reference type starts as null, which is where most NullPointerExceptions come from.

Every primitive type has a wrapper class (Integer, Double and so on) so that numbers can be stored in collections, which need objects. Java converts between them automatically; see autoboxing for how that works and where it costs memory and correctness.

Choosing a type

Which type to use
DataUseWhy
Counts, indexes, ordinary whole numbersintFast and the default for literals
Timestamps in milliseconds, IDs, file sizeslongint overflows at about 2.1 billion
Measurements, scientific valuesdoubleLarge range; small rounding errors are acceptable
MoneyBigDecimal or long centsdouble cannot represent most cents exactly
Integers beyond longBigIntegerNo size limit
Bytes from files or the networkbyte / byte[]Matches the data; mask with & 0xFF for 0 to 255
TextStringA single char cannot hold every character; see chars and code points
Yes/nobooleanClear intent

For bit-level work on these types, see bitwise operators, and for explicit casting of objects, see casting.