Java Data Types

A data type describes the kind of value a variable can hold and what you are allowed to do with it. Java splits every type into two families: the eight built-in primitive types, and reference types such as String and arrays that point to objects.

The two families of types

Primitive types are the simplest building blocks. They store a raw value directly, they are always lowercase, and there are exactly eight of them. Reference types, by contrast, store the address of an object that lives elsewhere in memory; String, arrays, and every class you write are reference types.

  • Primitive types: byte, short, int, long, float, double, char, and boolean.
  • Reference types: String, arrays, and objects of any class.
  • Primitives can never be null, while reference types can.
  • Primitive names are lowercase; reference type names start with a capital letter.

The eight primitive types

Each primitive type reserves a fixed amount of memory, which sets the range of values it can hold. Knowing these sizes helps you pick a type that is large enough for your data without wasting space.

TypeSizeHoldsExample
byte1 byteWhole numbers -128 to 127byte b = 100;
short2 bytesWhole numbers up to ~32,000short s = 5000;
int4 bytesWhole numbers up to ~2.1 billionint i = 100000;
long8 bytesVery large whole numberslong l = 9000000000L;
float4 bytesDecimals, ~6-7 digitsfloat f = 3.14f;
double8 bytesDecimals, ~15 digitsdouble d = 3.14159;
char2 bytesA single characterchar c = 'J';
boolean1 bittrue or falseboolean t = true;

Choosing a type in practice

Most everyday code uses just a few of these. Reach for int for whole numbers, double for anything with a decimal point, boolean for yes-or-no flags, and String for text. The narrower types like byte and short exist mainly to save memory when you have huge amounts of data.

A mix of primitive types

public class Main {
  public static void main(String[] args) {
    int items = 12;
    double weight = 4.75;
    char section = 'B';
    boolean inStock = true;
    System.out.println(items + " items, " + weight + " kg, section " + section + ", in stock: " + inStock);
  }
}

Default values

When a primitive is a field of a class and you do not set it, Java gives it a sensible default: zero for numbers, false for boolean, and the null character for char. Local variables inside methods, however, get no default and must be assigned before use.

String is a reference type

public class Main {
  public static void main(String[] args) {
    String message = "Data types in Java";
    System.out.println(message.length());
  }
}
Note: String is not a primitive type, even though it feels like one. It is a class, which is why it starts with a capital S and offers helpful methods such as length() and toUpperCase().

Exercise: Java Data Types

What type does Java assign to a decimal literal like 3.14 by default?