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
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, whereint could be 16 or 32 bits depending on the machine.int - Reference types are everything else: classes, interfaces, arrays, enums and records. A variable of type
orString holds a reference, which points to an object stored on the heap. Several variables can refer to the same object, and a reference can beList .null
| Type | Size | Holds | Default | Typical use |
|---|---|---|---|---|
byte | 8 bits | Whole numbers -128 to 127 | 0 | Raw binary data, files, network |
short | 16 bits | -32,768 to 32,767 | 0 | Rare; large arrays where memory matters |
int | 32 bits | About ±2.1 billion | 0 | The default for whole numbers |
long | 64 bits | About ±9.2 × 1018 | 0 | Timestamps, IDs, large counts |
float | 32 bits | About 7 significant decimal digits | 0.0 | Graphics, large arrays of measurements |
double | 64 bits | About 15 to 17 significant digits | 0.0 | The default for fractional numbers |
char | 16 bits | One UTF-16 code unit, 0 to 65,535 | '\u0000' | Characters of text |
boolean | Not specified | truefalse | false | Conditions 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 (IntegerLong
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:
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:
runs from -128 to 127.byte is the only unsigned type, 0 to 65,535. It is a number underneath, which is whychar is 65.(int) 'A'- For
andfloat ,double is the smallest positive value, not the most negative one. The most negativeMIN_VALUE isdouble . This naming catches many people writing "find the maximum" loops that start from-Double.MAX_VALUE .Double.MIN_VALUE - The size of a
is not defined by the language. In practice aboolean field or array element takes one byte in HotSpot.boolean
Writing literals
A literal is a value written directly in source code. Its form decides its type: 5int5Llong5.0double5.0ffloat
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:
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 is hexadecimal 255 and0xFF is binary 170.0b1010_1010- A leading zero makes a number octal:
is 8, not 10. Zero-padding a number for alignment, such as010 , changes its value, andint month = 08; does not even compile because 8 is not an octal digit.08 - Without the
,L would not compile: the literal is an9_000_000_000 and too large. Without theint ,f is a1.5 and cannot be assigned to adouble without a cast.float - Characters are numbers:
is the'A' + 1 66, and casting back givesint .'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.
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:
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
wraps around toInteger.MAX_VALUE + 1 with no error.Integer.MIN_VALUE ,Math.addExact ,subtractExact andmultiplyExact throwtoIntExact instead, which turns a silent wrong result into a visible one.ArithmeticException gives -727,379,968 even though along wrong = 1_000_000 * 1_000_000 could hold a trillion. Both operands arelong , so the multiplication happens in 32 bits and overflows; only the wrong result is widened toint . Making one operand along (long ) makes the whole multiplication 64-bit.1_000_000L- 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
for negative indexes;index % size gives 2, andMath.floorMod(-7, 3) rounds toward negative infinity.Math.floorDiv - Integer division by zero throws
. Floating-point division by zero does not, as the next section shows.ArithmeticException is still negative, because +2,147,483,648 does not fit in anMath.abs(Integer.MIN_VALUE) . Code that computesint can therefore produce a negative index.Math.abs(hashCode()) % n
Floating point: why 0.1 + 0.2 is not 0.3
floatdoublefloatdouble
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:
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
, which is slightly more than 0.1, and so is 0.2; their sum rounds to 0.30000000000000004, which is a differentdouble from the one nearest 0.3.double - The
sum prints 0.3 because it happens to round to thefloat nearest 0.3, and printing shows the shortest text that identifies thatfloat . It is still not exactly 0.3;float is less precise, not more.float - A
has 24 bits of precision, so 16,777,217 (224 + 1) cannot be stored and becomes 16,777,216. Afloat runs out at 253: near 1016 neighbouring doubles are 2.0 apart, so adding 1 changes nothing.double gives this gap.Math.ulp - Floating-point division by zero gives
orInfinity , and 0.0 / 0 gives-Infinity (not a number).NaN is not equal to anything, itself included, so test withNaN .Double.isNaN is0.0 == -0.0 , buttrue treats them as different, as it does withDouble.equals (whereNaN returnsequals ). This matters for map keys and for sorting.true- 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 intlongdoubleint
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:
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
toint is automatic, yet 1,234,567,890 became 1,234,567,936: afloat keeps the magnitude but only about 7 significant digits. The same happens fromfloat tolong above 253.double - Narrowing between integer types keeps only the low bits: 200 is
in binary, which as a signed11001000 is -56.byte - 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
becomes 0. UseNaN ,Math.round orfloor when you want rounding;ceil rounds halves up, so -2.5 becomes -2.Math.round - Arithmetic on
,byte andshort is done inchar , soint does not compile. Compound assignment such asbyte z = x + y contains a hidden cast back tox += y , which is why it compiles, and also why 120 + 10 silently became -126.byte - In a mixed expression, the narrower operand is promoted to the wider type:
is a5 / 2.0 division. With adouble ,String means concatenation, so+ is "a1" while"a" + 1 is 98.'a' + 1
| From | To | Automatic? | What can go wrong |
|---|---|---|---|
byteshortchar | int | Yes | Nothing |
int | longdouble | Yes | Nothing |
intlong | floatlongdouble | Yes | Lost precision for large values |
| A wider integer | A narrower integer | Cast needed | High bits dropped; sign can flip |
doublefloat | Any integer type | Cast needed | Fraction dropped; out-of-range values clamped |
double | float | Cast needed | Precision 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
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:
number: 1, items: [added]
a[0] after b[0] = 100: 100
int 0, double 0.0, boolean false
char code 0, String null
- Setting
inside the method changed the method's own copy of the number, son = 99 is still 1.number changed the one list that both the caller and the method refer to. Had the method assignedlist.add("added") , 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".list = new ArrayList<>() copied the reference, sob = a changed the arrayb[0] = 100 refers to. Seeaarrays for how to make real copies.- Fields get default values (0, 0.0,
, the zerofalse ,char ); a field of a reference type starts asnull , which is where mostnull s come from.NullPointerException
Every primitive type has a wrapper class (IntegerDouble
Choosing a type
| Data | Use | Why |
|---|---|---|
| Counts, indexes, ordinary whole numbers | int | Fast and the default for literals |
| Timestamps in milliseconds, IDs, file sizes | long | int |
| Measurements, scientific values | double | Large range; small rounding errors are acceptable |
| Money | BigDecimallong | double |
Integers beyond long | BigInteger | No size limit |
| Bytes from files or the network | bytebyte[] | Matches the data; mask with & 0xFF |
| Text | String | A single char |
| Yes/no | boolean | Clear intent |
For bit-level work on these types, see