Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 201 ยท Variables and Types

Primitive Data Types

Learn Java's eight primitive types, their sizes, ranges and default values, how to write int, long, float and hex or binary literals, and how primitives differ from references.

Every variable in Java has a type, and the compiler checks it before your program ever runs. Java's types fall into two families. Primitive types are the eight built-in kinds of simple values: numbers, characters and true/false. Reference types are everything else: String, arrays, lists and every class you write.

Primitives are the atoms that all other data is built from. They are fast, they take a fixed amount of memory, and they behave the same on every computer, because the Java specification fixes their exact sizes. In this lesson you'll learn all eight, how to write their values in code, which one to pick for a job, and why the line between primitives and references matters so much in Java.

The eight primitive types

Java has exactly eight primitive types. Six of them are numbers, one is a character and one is a truth value:

Type Size Range Example literal
byte 8 bits -128 to 127 (byte) 42
short 16 bits -32,768 to 32,767 (short) 1200
int 32 bits -2,147,483,648 to 2,147,483,647 42, 1_000_000
long 64 bits about ยฑ9.22 ร— 10ยนโธ 42L, 9_000_000_000L
float 32 bits about ยฑ3.4 ร— 10ยณโธ, 6โ€“7 significant digits 3.14f
double 64 bits about ยฑ1.8 ร— 10ยณโฐโธ, 15โ€“17 significant digits 3.14, 6.02e23
char 16 bits '\u0000' to '\uffff' (0 to 65,535) 'A', '\n'
boolean not specified true or false true

A few facts stand out:

  • The four integer types (byte, short, int, long) are all signed: they hold negative and positive values. Java has no unsigned int like C or C++.
  • float and double are floating-point types that follow the IEEE 754 standard, the same format your CPU uses. They trade exactness for a huge range.
  • char is a 16-bit unsigned number that stands for a character. It's the only unsigned primitive.
  • boolean is not a number at all. You can't use 0 or 1 where Java expects true or false.

Every numeric primitive has a matching wrapper class in java.lang (Byte, Short, Integer, Long, Float, Double, Character, Boolean). You don't need wrappers yet, but they hold handy constants such as the smallest and largest value of each type. Run this to see the real limits:

Java The limits of each primitive type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The output shows 3.4028235E38 for float. That E38 is scientific notation: 3.4028235 ร— 10ยณโธ. Java prints very large and very small floating-point numbers this way.

The (int) in front of Character.MIN_VALUE is a cast: it turns the character into its numeric code so you can see it as a number. You'll learn all about casts in Type Casting and Conversion.

Choosing the right type

With eight types to choose from, beginners often wonder which one to use. In practice the choice is simple:

  • int is the default for whole numbers: counters, ages, indexes, quantities. Java's integer literals are int, array indexes are int, and most library methods take and return int.
  • long is for whole numbers that might pass about 2.1 billion: file sizes in bytes, database IDs, populations, and time in milliseconds (System.currentTimeMillis() returns a long).
  • double is the default for numbers with a fractional part: measurements, averages, scientific values. Decimal literals like 2.5 are double.
  • boolean is for yes/no facts: isLoggedIn, hasErrors, done.
  • char is for a single character, such as a grade 'A' or a separator ','.
  • byte shows up when you work with raw binary data: file contents, network packets, image pixels (byte[]).
  • short and float are rare. They save memory only in very large arrays, for example in graphics or audio code.

Don't reach for byte or short "to save memory" on a single variable. The JVM usually stores small local variables in 32-bit slots anyway, and arithmetic on them produces int results, which forces you to write casts everywhere.

Never use double or float for money. They store numbers in binary, so a value like 0.1 can't be represented exactly, and small errors creep into sums. Use whole cents in a long, or BigDecimal from BigInteger and BigDecimal.

Integer literals

A literal is a value written directly in your code, like 42 or true. Java lets you write whole numbers in four bases and adds a few helpers for readability:

Java
int decimal = 255;          // base 10, the usual way
int hex = 0xFF;             // base 16: prefix 0x (or 0X)
int binary = 0b1111_1111;   // base 2: prefix 0b (or 0B)
int octal = 0377;           // base 8: a leading zero (rarely what you want!)
long big = 9_000_000_000L;  // suffix L makes it a long

All four of the first lines store the same number, 255.

  • Underscores can go between digits to group them: 1_000_000, 0xFF_FF, 0b0101_1010. They're ignored by the compiler. You can't put one at the start or end of a number, or right next to the 0x or the L.
  • Hex (0x) is common for colors, bit masks and memory addresses. Binary (0b) makes individual bits visible.
  • A leading zero means octal. 010 is 8, not 10. This trips people up when they pad numbers with zeros, so never write int month = 09; (it doesn't even compile, because 9 isn't an octal digit).
  • An integer literal is an int unless it ends with L. Use an uppercase L: a lowercase l looks almost exactly like the digit 1.
Java Integer literals in different bases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

"integer number too large"

Because a plain literal is an int, a value above 2,147,483,647 fails to compile, even when the variable is a long:

Java A literal that is too large (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler stops with error: integer number too large and points at the number. The fix is one letter: 149_600_000_000L. The type of the variable on the left doesn't help, because Java checks the literal on its own first.

Floating-point literals

Any number with a decimal point or an exponent is a floating-point literal, and its type is double by default:

Java
double price = 19.99;
double avogadro = 6.022e23;     // 6.022 ร— 10^23
double tiny = 1.5e-9;           // 0.0000000015
double half = .5;               // legal, but 0.5 reads better
double whole = 3d;              // the d suffix is allowed but rarely needed
float ratio = 0.75f;            // f suffix required for float

Writing float ratio = 0.75; is a compile error: incompatible types: possible lossy conversion from double to float. Java refuses to squeeze a double into a smaller float without your say-so, so you add f to make the literal a float from the start.

float keeps only about 7 significant digits. That's why double is the everyday choice:

Java float vs double precision

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The float prints 33.333332 while the double prints 33.333333333333336. Both are approximations: the last digits are where the binary representation runs out. And 0.1 + 0.2 prints 0.30000000000000004, because neither 0.1 nor 0.2 has an exact binary form. Working with Numbers explains why this happens and how to deal with it.

char and boolean literals

A char literal is a single character in single quotes, and a boolean literal is true or false:

Java
char grade = 'A';
char newline = '\n';        // escape sequence
char omega = '\u03a9';      // Unicode escape: ฮฉ
boolean ready = true;

Double quotes make a String, not a char: "A" and 'A' are different types. Characters have their own lesson, Characters and Booleans, including what happens with emoji that don't fit in one char.

Small types and constant values

You may be surprised that this compiles:

Java
byte level = 100;      // OK: 100 fits in a byte
short year = 2025;     // OK: fits in a short
char letter = 65;      // OK: 65 is 'A'

The literal 100 is an int, yet Java lets you store it in a byte. The rule: when the value is a compile-time constant that fits in the target type, the compiler narrows it for you. A value that doesn't fit is an error:

Java
byte tooBig = 200;     // error: incompatible types: possible lossy conversion from int to byte

The same rule does not apply to variables, because the compiler can't be sure what they hold. int n = 100; byte b = n; fails even though 100 would fit. You'd need an explicit cast, as shown in Type Casting and Conversion.

Default values: fields vs local variables

What does a variable hold before you assign anything? It depends on where it lives.

Fields (variables declared in a class, outside any method) are automatically set to a default:

Type Default
byte, short, int, long 0
float, double 0.0
char '\u0000' (the character with code 0)
boolean false
any reference type null

Local variables (declared inside a method) get no default at all. Reading one before assigning it is a compile error: variable x might not have been initialized. This rule, called definite assignment, is covered in Variables.

In a compact source file, variables declared outside void main() are fields of the hidden class Java creates for you, so you can watch the defaults:

Java Default values of fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The char default is printed as its code, 0, because the character itself is invisible. Notice that String is a reference type, so its default is null, meaning "no object yet".

Primitives vs references

The biggest idea in this lesson is the difference between the two families of types.

A primitive variable holds the value itself. When you write int a = 5;, the variable a contains the bits for 5. Copying it copies the value.

A reference variable holds a reference (think of it as an address) to an object stored elsewhere in memory, on the heap. When you copy a reference, you get a second arrow pointing at the same object.

Java Copying a primitive vs copying a reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Changing b leaves a alone. But first and second are two names for one array, so changing it through either name shows up in both. Arrays and StringBuilder come later; for now, just notice the pattern.

Other differences follow from the same idea:

Primitive Reference
Holds the value a reference to an object
Can be null no yes
Name style lowercase keyword (int) class name (String, Integer)
== compares values whether two references point to the same object
Has methods no (5.length() is an error) yes ("hi".length())
Works in generics (List<...>) no yes

That last row is why wrapper classes exist: a List<int> is not allowed, so you write List<Integer> and Java converts between int and Integer automatically. Wrapper Classes and Autoboxing covers that conversion and its traps.

String looks like a built-in type because it has literals ("hello"), but it's a class: a reference type. That's why you compare strings with equals() rather than ==, as you'll see in Strings.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line fails to compile?

    Without the L suffix, 5_000_000_000 is an int literal, and it's larger than Integer.MAX_VALUE, so the compiler reports "integer number too large". The hex value 0x7FFF_FFFF is exactly Integer.MAX_VALUE, so it fits.
  2. 2. What does IO.println(012 + 1); print?

    A leading zero makes 012 an octal literal, which is 1 ร— 8 + 2 = 10 in decimal. Adding 1 gives 11.
  3. 3. Why does float rate = 0.5; fail to compile?

    0.5 is a double literal. Java won't silently narrow a double to a float, so you write 0.5f to make it a float literal.
  4. 4. A class has the field boolean active; that is never assigned. What is its value when you read it?

    Fields get default values, and the default for boolean is false. Only local variables must be assigned before use.
  5. 5. After int[] p = {1}; int[] q = p; q[0] = 7;, what is p[0]?

    Arrays are objects, so q = p copies the reference. Both variables point at the same array, and the change made through q is visible through p.

Summary

  • Java has eight primitive types: byte, short, int, long (signed integers), float, double (floating point), char (a 16-bit character code) and boolean.
  • Their sizes are fixed by the language, so they behave the same on every platform. Wrapper constants like Integer.MAX_VALUE show each range.
  • Use int for whole numbers, long when values may pass about 2.1 billion, double for decimals and boolean for yes/no. Never use floating point for money.
  • Integer literals can be decimal, hex (0x), binary (0b) or octal (leading 0); underscores improve readability; L makes a long.
  • Decimal literals are double; add f for float.
  • Fields get default values (0, 0.0, false, '\u0000', null); local variables must be assigned before use.
  • Primitive variables hold values; reference variables hold references to objects, so copying a reference shares the object.

Next: Working with Numbers, where you'll see integer division, overflow, floating-point surprises and how to handle them safely.