Java Primitive Types: Integers and Floating-Point Numbers Explained
Java's eight primitive types, with a deep dive into byte, short, int, long, float and double: their sizes and ranges, number literals (hex, binary, underscores), overflow, unsigned tricks, floating-point rounding errors, Infinity and NaN.
kvi5hnuCode Sprout team member13 min readOn this page
Java is a strongly (statically) typed language: every variable has a type that is fixed when you write the program, and the compiler checks that you use each value according to its type. The type determines how much memory a value takes, which values it can hold, and which operations are allowed.
Java has exactly eight primitive types, built into the language:
| Category | Types | Holds |
|---|---|---|
| Integer types | byte, short, int, long | Whole numbers, positive or negative |
| Floating-point types | float, double | Numbers with fractional parts |
| Character type | char | A UTF-16 code unit (part of a text character) |
| Boolean type | boolean | true or false |
Everything else in Java, including strings, arrays and your own classes, is a reference type (an object). Primitive values are stored directly and are very fast; objects are covered in later parts.
This article covers the six numeric types. The next one covers char, Unicode and boolean.
The Four Integer Types
Integer types hold whole numbers, without a fractional part. Negative values are allowed.

| Type | Size | Minimum | Maximum | Constant names |
|---|---|---|---|---|
byte | 1 byte (8 bits) | −128 | 127 | Byte.MIN_VALUE, Byte.MAX_VALUE |
short | 2 bytes (16 bits) | −32,768 | 32,767 | Short.MIN_VALUE, Short.MAX_VALUE |
int | 4 bytes (32 bits) | −2,147,483,648 | 2,147,483,647 | Integer.MIN_VALUE, Integer.MAX_VALUE |
long | 8 bytes (64 bits) | −9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 | Long.MIN_VALUE, Long.MAX_VALUE |
The pattern: an n-bit type holds values from −2ⁿ⁻¹ to 2ⁿ⁻¹ − 1. There's one more negative value than positive, because zero takes one of the non-negative slots.
Which one should you use?
intis the default. Counters, indexes, ages, quantities: useintunless you have a reason not to. Integer literals like42areint, and arithmetic on smaller types is carried out inintanyway.longwhen values may exceed about 2.1 billion: the world's population (about 8.1 billion), file sizes in bytes, milliseconds since 1970 (System.currentTimeMillis()returns along), database IDs.byteandshortare for special purposes: raw binary data from files and networks (byte[]), or very large arrays where memory matters. Don't use them just because "the value is small". It brings no benefit and causes casting headaches.
Same size everywhere
These ranges are the same on every machine. In C and C++, by contrast, the sizes of int and long depend on the compiler and processor: an int was 2 bytes on 16-bit processors and 4 bytes on 32-bit ones, and long is 4 bytes on some 64-bit platforms (Windows) and 8 on others (Linux). A C program that works fine on one platform can overflow on another. Java fixed the sizes so that programs produce the same results everywhere.
Integer Literals
A literal is a value written directly in the code. Java lets you write integers in four bases:
| Form | Prefix | Example | Value |
|---|---|---|---|
| Decimal | none | 202 | 202 |
| Hexadecimal (base 16) | 0x or 0X | 0xCA | 202 |
| Binary (base 2) | 0b or 0B | 0b1100_1010 | 202 |
| Octal (base 8) | 0 (a leading zero) | 0312 | 202 |
Two more rules:
- Underscores may separate digits for readability:
1_000_000,0b1111_0000. The compiler simply ignores them. (They may not start or end a number or sit next to the prefix or suffix.) - A literal is an
intby default. For along, add the suffixL:8_100_000_000L. Use uppercaseL, since lowercasellooks like the digit1. A literal too large forintwithout theLis a compile error ("integer number too large").
public class Solution {
public static void main(String[] args) {
int decimal = 202;
int hex = 0xCA; // hexadecimal
int octal = 0312; // octal: leading zero!
int binary = 0b1100_1010; // binary, with an underscore
long big = 8_100_000_000L; // needs L: too large for int
System.out.println(decimal + " " + hex + " " + octal + " " + binary);
System.out.println("World population (approx.): " + big);
System.out.println(010 + 10); // surprise: 010 is octal 8
}
}
202 202 202 202
World population (approx.): 8100000000
18
Integer Overflow: Values Wrap Around
What happens when a calculation produces a value outside the type's range? Java does not report an error. The result wraps around to the other end of the range, as if the values were arranged in a circle:

public class Solution {
public static void main(String[] args) {
int max = Integer.MAX_VALUE;
System.out.println("max = " + max);
System.out.println("max + 1 = " + (max + 1)); // wraps around
byte b = 127;
b++;
System.out.println("byte 127 + 1 = " + b);
long safe = (long) max + 1;
System.out.println("as long = " + safe);
try {
int boom = Math.addExact(max, 1); // detects overflow
System.out.println(boom);
} catch (ArithmeticException e) {
System.out.println("addExact: " + e.getMessage());
}
}
}
max = 2147483647
max + 1 = -2147483648
byte 127 + 1 = -128
as long = 2147483648
addExact: integer overflow
Why does it wrap? Integers are stored in two's complement binary. The largest int is 0111…1 (a 0 followed by 31 ones). Adding 1 gives 1000…0, and in two's complement a leading 1 bit means a negative number, here the most negative one. The behaviour is precisely defined and identical on every JVM. (In C and C++, signed overflow is undefined behaviour.)
Silent overflow is a classic source of bugs: a counter that goes negative, a sum of large values that becomes nonsense. Ways to protect yourself:
| Technique | Example |
|---|---|
| Use a wider type when values can be large | long total = 0; |
| Convert before computing, not after | (long) max + 1, not (long) (max + 1) |
Use the "exact" methods, which throw ArithmeticException on overflow | Math.addExact, Math.subtractExact, Math.multiplyExact, Math.incrementExact, Math.toIntExact |
Use BigInteger for arbitrarily large values | see the big-numbers article |
No Unsigned Types (and How to Cope)
Unlike C, Java has no unsigned integer types. Every integer type can hold negative numbers. Usually that's fine, but sometimes you need the full non-negative range, for example when a byte from a file represents a value from 0 to 255.
The bits are the same either way; only the interpretation differs. The byte with bits 11001000 means −56 as a signed byte and 200 as an unsigned one. Addition, subtraction and multiplication give the correct bits for both interpretations (as long as they don't overflow). For everything else, the wrapper classes offer unsigned helpers:
public class Solution {
public static void main(String[] args) {
byte raw = (byte) 200; // stored as -56
System.out.println("signed: " + raw);
System.out.println("unsigned: " + Byte.toUnsignedInt(raw));
int big = -1; // all 32 bits set
System.out.println(Integer.toUnsignedString(big)); // 4294967295
System.out.println(Integer.divideUnsigned(big, 2)); // 2147483647
System.out.println(Integer.toBinaryString(-56));
}
}
signed: -56
unsigned: 200
4294967295
2147483647
11111111111111111111111111001000
| Method | Purpose |
|---|---|
Byte.toUnsignedInt(b), Short.toUnsignedInt(s) | Read a byte/short as 0…255 / 0…65,535 |
Integer.toUnsignedLong(i) | Read an int as 0…4,294,967,295 |
Integer.divideUnsigned, Integer.remainderUnsigned, Integer.compareUnsigned | Unsigned arithmetic and comparison (also in Long) |
Integer.toUnsignedString, Integer.parseUnsignedInt | Unsigned conversion to and from text (also in Long) |
The usual pattern: convert to a wider type with the toUnsigned… method, compute, then cast back if needed.
The Two Floating-Point Types
Floating-point types hold numbers with fractional parts, such as 3.14, −0.001 or 6.02 × 10²³.
| Type | Size | Approximate range | Precision | Literal |
|---|---|---|---|---|
float | 4 bytes | ±3.40282347 × 10³⁸ | about 6–7 significant decimal digits | 3.14F or 3.14f |
double | 8 bytes | ±1.79769313486231570 × 10³⁰⁸ | about 15–17 significant decimal digits | 3.14 (or 3.14D) |
The name double refers to double precision: twice the precision of float.
Use double by default. Seven significant digits (float) is simply not enough for many calculations: the difference shows up as soon as you add many values or need more than a few decimal places. Use float only when a library requires it (graphics and machine-learning APIs often do), or when you store a huge number of values and memory matters.
Floating-point literal rules:
- A number with a decimal point or exponent is a
doubleunless it ends inF/f. Writingfloat f = 3.14;is a compile error ("possible lossy conversion from double to float"); write3.14F. Eoreintroduces a decimal exponent:1.729E3= 1.729 × 10³ = 1729.0;6.02e23;1e-9.- Hexadecimal floating-point literals exist for exact bit patterns:
0x1.0p-3= 1 × 2⁻³ = 0.125. The exponent afterpis a power of 2, written in decimal (anewould be a hex digit).
How floating-point numbers are stored
Java's float and double follow the international IEEE 754 standard, like nearly all modern hardware. A floating-point number is stored like scientific notation, but in binary: a sign, an exponent and a fraction (mantissa).

The fraction bits determine the precision (how many significant digits); the exponent bits determine the range (how large or small the number can be).
Rounding Errors: Why 0.1 + 0.2 Isn't 0.3
public class Solution {
public static void main(String[] args) {
System.out.println(2.0 - 1.1);
System.out.println(0.1 + 0.2);
System.out.println(0.1 + 0.2 == 0.3);
float f = 3.14159265358979F;
double d = 3.14159265358979;
System.out.println("float : " + f);
System.out.println("double: " + d);
System.out.println(1.729E3 + " " + 0x1.0p-3);
}
}
0.8999999999999999
0.30000000000000004
false
float : 3.1415927
double: 3.14159265358979
1729.0 0.125
This isn't a Java bug. It happens in every language that uses binary floating point (C, Python, JavaScript…). The reason: just as 1/3 can't be written exactly in decimal (0.3333…), 1/10 can't be written exactly in binary. It's an infinitely repeating binary fraction (0.000110011001100…), so 0.1 is stored as the nearest representable value, slightly off. Tiny errors in 0.1 and 0.2 add up to a result that's not exactly the stored value of 0.3.
Practical consequences:
- Never use
float/doublefor money. A cent here and there adds up, and accountants (and auditors) notice. UseBigDecimal, or count in whole cents withlong. - Don't compare floating-point results with
==. Check whether they're close enough instead:
double a = 0.1 + 0.2;
boolean same = Math.abs(a - 0.3) < 1e-9; // true
- Format output instead of printing raw values:
System.out.printf("%.2f", 2.0 - 1.1)prints0.90. Formatting is covered in the console I/O article.
Special Values: Infinity and NaN
IEEE 754 defines three special values for results that aren't ordinary numbers:
| Value | When it appears | Constant |
|---|---|---|
| Positive infinity | A positive number divided by 0.0, or a result too large to represent | Double.POSITIVE_INFINITY |
| Negative infinity | A negative number divided by 0.0 | Double.NEGATIVE_INFINITY |
| NaN ("not a number") | 0.0 / 0, the square root of a negative number, Infinity - Infinity | Double.NaN |
public class Solution {
public static void main(String[] args) {
System.out.println(1.0 / 0);
System.out.println(-1.0 / 0);
System.out.println(0.0 / 0);
System.out.println(Math.sqrt(-4));
double x = 0.0 / 0;
System.out.println(x == Double.NaN);
System.out.println(Double.isNaN(x));
System.out.println(Double.MAX_VALUE + " " + Double.MIN_VALUE);
System.out.println(Float.MAX_VALUE);
}
}
Infinity
-Infinity
NaN
NaN
false
true
1.7976931348623157E308 4.9E-324
3.4028235E38
Important details:
- Floating-point division by zero doesn't throw an exception. It produces infinity or NaN. Integer division by zero (
1 / 0) does throw anArithmeticException. The difference surprises many beginners. - NaN isn't equal to anything, not even itself.
x == Double.NaNis always false. To test for NaN, useDouble.isNaN(x). Similarly,Double.isInfinite(x)andDouble.isFinite(x)exist. Double.MIN_VALUEis the smallest positive double (about 4.9 × 10⁻³²⁴), not the most negative one. The most negative double is-Double.MAX_VALUE. This naming catches many people out.
Common questions
Why does 0.1f + 0.2f print 0.3 when 0.1 + 0.2 doesn't?
Both sums contain rounding errors. With float, the nearest representable result happens to print as 0.3, because Java prints only as many digits as needed to identify the value. With double, the error shows up in the shortest unique representation (0.30000000000000004). This makes float look more accurate, but it isn't. It is less precise, and you just can't see it here.
Is -0.0 a real thing?
Yes. IEEE 754 has a negative zero, which you get from results such as -1.0 / Double.POSITIVE_INFINITY. 0.0 == -0.0 is true, but Double.compare(0.0, -0.0) returns 1, and 1 / -0.0 is negative infinity. It rarely matters outside numerical code, but it explains some surprising results from equals and compare.
What is the maximum value of long, and what happens if I add 1?
It is Long.MAX_VALUE, 9,223,372,036,854,775,807 (about 9.2 × 10¹⁸). Adding 1 wraps around to Long.MIN_VALUE without any error, just like int. Use Math.addExact when overflow would be a bug, or BigInteger when values really can be that large.
Should I use float to save memory?
Only when you store very many values, such as millions of array elements, and seven significant digits are enough. A single float variable saves nothing that matters, and lost precision causes real bugs. double is the default for a reason.
Will Java get unsigned or 128-bit integer types?
There are no plans for new primitive types of that kind. Project Valhalla's value classes are expected to let libraries define efficient number-like types. For now, use the unsigned helper methods on Integer and Long, Math.multiplyHigh for the upper 64 bits of a product, or BigInteger.
Summary
- Java has eight primitive types: four integer types, two floating-point types,
charandboolean. Their sizes are fixed on every platform. int(32 bits, ±2.1 billion) is the default integer type; uselong(64 bits, suffixL) for larger values;byteandshortare for binary data and huge arrays.- Literals can be decimal, hex (
0x), binary (0b) or octal (leading0, a trap); underscores improve readability. - Integer overflow wraps around silently. Use
long,Math.addExactand friends, orBigIntegerwhen it matters. - Java has no unsigned types;
Byte.toUnsignedInt,Integer.toUnsignedString,Integer.divideUnsignedand similar methods handle unsigned interpretations. double(about 15–17 digits) is the default floating-point type;float(suffixF, about 6–7 digits) only when required.- Binary floating point can't represent most decimal fractions exactly: never use it for money, and don't compare results with
==. - Floating-point division by zero gives Infinity or NaN, not an exception; test for NaN with
Double.isNaN.
Practice Questions
Which type would you choose for: a person's age, the number of bytes in a 10 GB file, a temperature like 21.5 °C, a raw byte from a network packet?
Age: int. File size: long (10 GB is about 10.7 billion bytes, more than int can hold). Temperature: double. Raw network byte: byte (often read via Byte.toUnsignedInt to get 0…255).
What does System.out.println(Integer.MAX_VALUE + 1) print, and why is no error reported?
-2147483648. Integer arithmetic in Java wraps around on overflow: the bit pattern after adding 1 to the largest int is the most negative int in two's complement. Java defines this behaviour and doesn't check for it; use Math.addExact if you want an exception.
Why does long x = 3_000_000_000; not compile, while long x = 3_000_000_000L; does?
Without a suffix, an integer literal is an int, and 3,000,000,000 exceeds Integer.MAX_VALUE, so the compiler reports "integer number too large". The L suffix makes the literal a long.
What is the value of 0x10 + 010 + 0b10 + 10?
16 + 8 + 2 + 10 = 36. 0x10 is hexadecimal 16, 010 is octal 8, 0b10 is binary 2, and 10 is decimal.
A colleague writes if (result == Double.NaN) to detect an invalid calculation. What is wrong?
NaN is never equal to anything, including itself, so the condition is always false. Use Double.isNaN(result).
What do 1 / 0 and 1.0 / 0 do?
1 / 0 is integer division and throws ArithmeticException: / by zero. 1.0 / 0 is floating-point division and evaluates to Infinity, with no exception.
Why should you not store prices as double?
Most decimal fractions (like 0.10) have no exact binary representation, so prices stored as double carry tiny rounding errors that accumulate in sums and comparisons (0.1 + 0.2 is 0.30000000000000004). Use BigDecimal or whole cents in a long.
Previous: Your First Java Program Explained: Classes, main, Statements and Comments
Next: Java char, Unicode and boolean: Characters, Escape Sequences and Truth Values
Related reading
- Java Collectors.toMap: Collecting Streams into Maps
- Collecting Java Stream Results: toList, toArray, joining and Summary Statistics
- Java Optional Best Practices: Pitfalls, Creating Optionals, flatMap and stream()
- Java Optional: Getting, Consuming and Transforming Optional Values
- Java Stream Reductions: count, max, min, findFirst, findAny and anyMatch

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.