- Prerequisites
- 2.3 Variables · 2.4 Operators
- Covers
- byte · short · int · long · float · double · char · boolean
- Related
- 3.3 Primitive vs Reference · 3.4 Type Conversion · 3.5 Wrapper Classes
On this page
1Concept / Definition
A primitive type is a built-in type whose variables hold the value itself, not a reference to an object. Java has exactly eight, and — unlike C — their sizes and behaviour are fixed by the language specification on every platform.

2Why It Exists
Making everything an object would be simpler conceptually, but far slower and larger: every number would need a heap allocation and a header. Primitives give Java direct, compact storage for numbers and flags, mapping closely to CPU registers, while fixing their sizes gives the portability described in 1.3.
3Core Concepts
| Type | Size | Range / precision | Default | Literal examples |
|---|---|---|---|---|
| byte | 8 bits | -128 … 127 | 0 | (byte) 10 |
| short | 16 bits | -32,768 … 32,767 | 0 | (short) 1000 |
| int | 32 bits | -2,147,483,648 … 2,147,483,647 | 0 | 42, 0x2A, 0b101010, 1000000 |
| long | 64 bits | ≈ ±9.22 × 10^18 | 0L | 42L, 3000000_000L |
| float | 32 bits | ≈ 6–7 significant decimal digits | 0.0f | 3.14f, 1e-3f |
| double | 64 bits | ≈ 15–16 significant decimal digits | 0.0 | 3.14, 1e-3, 2.5d |
| char | 16 bits | 0 … 65,535 (UTF-16 code unit) | '\u0000' | 'A', '\n', '\u20B9' |
| boolean | not specified | true or false | false | true, false |
byte
An 8-bit signed integer. Used for raw binary data — file contents, network packets, cryptographic buffers — almost always in byte[]. Arithmetic on bytes is performed in int (2.4), so results must be cast back.
short
A 16-bit signed integer. Rarely used in application code; it appears in binary formats and memory-sensitive arrays. Like byte, it is promoted to int in arithmetic.
int
A 32-bit signed integer in two's complement form — the default integer type. Integer literals are int unless suffixed with L. Overflow wraps silently: adding 1 to the maximum value gives the minimum value.

long
A 64-bit signed integer, needed for values beyond about 2.1 billion: identifiers, byte counts, timestamps in milliseconds or nanoseconds, and money in minor units. Literals need the L suffix; 3_000_000_000 without it does not compile.
float
A 32-bit IEEE 754 binary floating-point number with about 7 significant decimal digits. Use it only when memory for very large arrays matters (graphics, machine-learning buffers); otherwise prefer double. Literals need the f suffix.
double
A 64-bit IEEE 754 binary floating-point number and the default for decimal literals. Binary floating point cannot represent most decimal fractions exactly, which is why it must not be used for money. It also has special values: positive and negative infinity, NaN (not a number) and negative zero.

char
A 16-bit unsigned value holding one UTF-16 code unit. Most common characters fit in one char, but characters outside the Basic Multilingual Plane — many emoji, some CJK characters — need two (a surrogate pair). char is numeric: 'A' + 1 is the int 66.
boolean
Holds true or false and is not a number: it cannot be converted to or from an integer. The JLS does not define its size; HotSpot typically uses an int on the operand stack and one byte per element in a boolean[].
4How It Works Internally
The JLS fixes the range and arithmetic of each type; the JVM decides how to hold it. On the operand stack and in local variables there are only four computational types: int, long, float and double. A boolean, byte, char or short is loaded as an int, which is why byte + byte compiles to iadd and produces an int (2.4), and long and double take two slots (Figure 4). In arrays and fields, values are stored at their real size, so a byte[] of a million elements takes a megabyte, and the load instructions restore the type: baload sign-extends a byte, caload zero-extends a char because char is unsigned.

Integer types are stored in two's complement, and the CPU's own add and multiply instructions are used without overflow checks, which is why wrapping costs nothing and detecting it needs Math.addExact. float and double use the CPU's IEEE 754 hardware; since Java 17 every operation is strict, so results are bit-for-bit identical on every platform. A char is a UTF-16 code unit, not a character: characters above U+FFFF need two (Figure 5), and String stores text as Latin-1 bytes or UTF-16 internally (compact strings), which is invisible to code that uses the String API.

5APIs / Features / Syntax
int big = Integer.MAX_VALUE; // 2147483647
long safe = Math.addExact(big, 1L); // 2147483648, no overflow in long
int hex = 0xFF, bin = 0b1010, readable = 1_000_000;
double nan = 0.0 / 0.0;
boolean isNan = Double.isNaN(nan); // use this, never nan == nan
String bits = Integer.toBinaryString(-5); // 11111111111111111111111111111011
// stored as negative int
int unsigned = Integer.parseUnsignedInt("4000000000");
String text = Integer.toUnsignedString(unsigned); // "4000000000"6Practical Examples
Example 1 — Floating point and char behaviour
System.out.println(0.1 + 0.2); // 0.30000000000000004
System.out.println(0.1f + 0.2f); // 0.3 (by rounding luck, less precise)
System.out.println(1.0 / 0); // Infinity
System.out.println(0.0 == -0.0); // true
System.out.println(Double.NaN == Double.NaN); // false
char c = 'A';
c += 2; // 'C' (compound assignment casts back)
int code = 'A' + 1; // 66
String rupee = "₹"; // one char: '\u20B9'
String smile = "😀"; // two chars (surrogate pair)
System.out.println(smile.length()); // 2
System.out.println(smile.codePointCount(0, 2)); // 1Every comment is the real output (kit class FloatChar).
Example 2 — Mini program: the limits of every primitive type
Problem. The table in section 3 gives the ranges; this program prints them from the wrapper constants and then shows the three ways values silently stop being what they seem: wrapping, lost integer precision in float, and growing gaps between double values.
public class PrimitiveLimits {
static void row(String type, int bits, Object min, Object max) {
System.out.printf("%-6s %4d %21s %22s%n", type, bits, min, max);
}
public static void main(String[] args) {
System.out.printf("%-6s %4s %21s %22s%n", "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);
int max = Integer.MAX_VALUE;
float f = 16_777_217; // 2^24 + 1
System.out.println("int max + 1 = " + (max + 1)); // wraps
System.out.println("float 16777217 = " + (long) f); // nearest float
System.out.println("ulp(1.0) = " + Math.ulp(1.0)); // gap
System.out.println("ulp(1e16) = " + Math.ulp(1e16)); // gap grows
System.out.println("1e16 + 1 == 1e16: " + (1e16 + 1 == 1e16));
System.out.println("(char) 65 = " + (char) 65);
System.out.println("'A' + 1 = " + ('A' + 1));
}
}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
int max + 1 = -2147483648
float 16777217 = 16777216
ulp(1.0) = 2.220446049250313E-16
ulp(1e16) = 2.0
1e16 + 1 == 1e16: true
(char) 65 = A
'A' + 1 = 66Why it behaves this way. The integer ranges are asymmetric, one more negative value than positive, because of two's complement. Float.MIN_VALUE and Double.MIN_VALUE are the smallest positive values, not the most negative ones, a classic surprise. A float has 24 bits of precision, so 16,777,217 (2^24 + 1) is rounded to 16,777,216. Math.ulp gives the gap to the next representable value: about 2.2e-16 after 1.0 but 2.0 after 1e16, so adding 1 to 1e16 changes nothing. That is why double is fine for measurements and wrong for identifiers or exact counts above 2^53.
Example 3 — Counting characters: char versus code point
Problem. A form limits names to 20 characters with name.length(), and a report cuts names with substring. Both use chars, not characters. The program compares the two counts for four strings and cuts an emoji in the middle.
public class CodePoints {
static void show(String label, String s) {
StringBuilder cps = new StringBuilder();
s.codePoints().forEach(cp -> cps.append(String.format(" U+%04X", cp)));
System.out.printf("%-6s length=%d codePoints=%d%s%n",
label, s.length(), s.codePointCount(0, s.length()), cps);
}
public static void main(String[] args) {
show("A", "A");
show("rupee", "\u20B9");
show("emoji", "\uD83D\uDE00"); // one character, two chars
show("naive", "na\u00EFve");
String emoji = "\uD83D\uDE00";
boolean high = Character.isHighSurrogate(emoji.charAt(0));
System.out.println("high surrogate: " + high);
String half = emoji.substring(0, 1); // cuts the pair in two
System.out.println("substring(0,1): " + (int) half.charAt(0));
int end = emoji.offsetByCodePoints(0, 1); // after one code point
String whole = emoji.substring(0, end);
System.out.println("by code point : " + whole.codePointAt(0));
}
}A length=1 codePoints=1 U+0041
rupee length=1 codePoints=1 U+20B9
emoji length=2 codePoints=1 U+1F600
naive length=5 codePoints=5 U+006E U+0061 U+00EF U+0076 U+0065
high surrogate: true
substring(0,1): 55357
by code point : 128512Why it behaves this way. length() counts UTF-16 code units. The rupee sign and ï are in the Basic Multilingual Plane, so they are one char each, but the emoji U+1F600 is stored as the surrogate pair D83D DE00 and counts as 2. substring(0, 1) keeps only the high surrogate, 55357, which is not a character on its own and is shown as a replacement symbol wherever it is displayed. offsetByCodePoints finds the end of a whole code point, and codePointCount gives the count people expect. (Even code points are not always what users see as one character; accents and emoji sequences can combine several, which java.text.BreakIterator handles.)
Example 4 — Comparing floating-point values
Problem. A test compares a computed price with == and fails intermittently; another sorts measurements containing NaN. The program shows what each comparison really does.
import java.math.BigDecimal;
public class DoubleCompare {
static boolean close(double a, double b, double eps) { // relative
double scale = Math.max(1.0, Math.max(Math.abs(a), Math.abs(b)));
return Math.abs(a - b) <= eps * scale;
}
public static void main(String[] args) {
double sum = 0.1 + 0.2;
double nan = Double.NaN;
System.out.println("sum == 0.3 : " + (sum == 0.3));
System.out.println("close(sum, 0.3, 1e-9) : " + close(sum, 0.3, 1e-9));
System.out.println("NaN == NaN : " + (nan == nan));
System.out.println("compare(NaN, NaN) : "
+ Double.compare(nan, nan));
System.out.println("0.0 == -0.0 : " + (0.0 == -0.0));
System.out.println("compare(0.0, -0.0) : "
+ Double.compare(0.0, -0.0));
BigDecimal exact = new BigDecimal("0.1").add(new BigDecimal("0.2"));
BigDecimal target = new BigDecimal("0.3");
System.out.println("BigDecimal sum : " + exact
+ ", compareTo 0.3: " + exact.compareTo(target));
System.out.println("new BigDecimal(0.1):");
System.out.println(new BigDecimal(0.1));
}
}sum == 0.3 : false
close(sum, 0.3, 1e-9) : true
NaN == NaN : false
compare(NaN, NaN) : 0
0.0 == -0.0 : true
compare(0.0, -0.0) : 1
BigDecimal sum : 0.3, compareTo 0.3: 0
new BigDecimal(0.1):
0.1000000000000000055511151231257827021181583404541015625Why it behaves this way. == follows IEEE 754: NaN is unequal to everything, and 0.0 equals -0.0. Double.compare defines a total order instead, with NaN equal to itself and above every other value, and -0.0 below 0.0; sorting and Double.equals use it. For computed results, compare with a tolerance relative to the size of the values. When exactness matters, use BigDecimal built from a String: new BigDecimal(0.1) shows the exact binary value that the literal 0.1 really stores.
7Common Problems & Mistakes
| Mistake | Why it hurts | Better approach |
|---|---|---|
| double for money | 0.1 + 0.2 is 0.30000000000000004; totals drift and do not reconcile | BigDecimal, or long in minor units (paise, cents) |
| int for IDs, byte counts or epoch milliseconds | Values pass 2^31 sooner than expected and wrap to negative numbers | long |
| Comparing doubles with == | Rounding makes equal results differ; NaN is never equal, even to itself | Compare with a tolerance, or use BigDecimal; test NaN with Double.isNaN (Example 4) |
| Assuming one char is one character | Lengths are wrong and substring can split an emoji in two | Use code points (codePoints(), codePointCount) for user text (Example 3) |
| Forgetting the L suffix on large literals | A compile error, or the arithmetic is done in int and overflows before widening | Write 3_000_000_000L; make the first operand long |
| Storing large IDs or counts in float or double | Integers above 2^24 (float) or 2^53 (double) are rounded | long, or String for external IDs |
| Reading Float.MIN_VALUE as the most negative float | It is the smallest positive value; range checks go wrong | -Float.MAX_VALUE, or Double.NEGATIVE_INFINITY as a start value |
8Performance & Production Considerations
- Primitives and primitive arrays are the most compact and cache-friendly storage Java has; performance-critical code avoids boxing them (3.5).
longanddoublewrites are not guaranteed atomic on all platforms unless the field isvolatile; in practice 64-bit JVMs are atomic, but the JMM does not promise it.
9Architecture & Design Considerations
Primitive types look like an implementation detail, but each choice becomes part of a contract once it reaches a database column, a message or an API. An int order number that is fine for a start-up fails when the platform passes 2.1 billion orders; a timestamp in int seconds fails in January 2038; a 64-bit ID sent as a JSON number is rounded by JavaScript clients above 2^53. Changing the type later means migrating data and every consumer at once.
Architects therefore set canonical types per concept and state them in API and data standards:
| Concept | Type in Java | At the boundary |
|---|---|---|
| Identifiers | long, or UUID | BIGINT; a string in JSON when clients use JavaScript |
| Money | BigDecimal, or long minor units with a currency | NUMERIC with a fixed scale, plus a currency code |
| Time | java.time types (Instant, Duration) | ISO 8601 strings or epoch milliseconds in a long |
| Counts, sizes | long | BIGINT; JSON number while below 2^53 |
| Measurements | double | DOUBLE PRECISION; document the unit in the name, e.g. latencyMs |
10Interview Questions & Answers
List Java's primitive types and their sizes.
byte (8 bits), short (16), int (32), long (64), float (32), double (64), char (16, unsigned UTF-16 code unit) and boolean (size not specified by the language). Their sizes are fixed by the JLS on every platform, unlike C, where int and long vary.
Why is 0.1 + 0.2 not equal to 0.3 in Java?
double is binary floating point. 0.1 and 0.2 have infinitely repeating binary expansions, so they are stored rounded, and their sum is rounded again to 0.30000000000000004. This is IEEE 754 behaviour, not a Java bug.
Is char a character?
It is a 16-bit UTF-16 code unit. Characters in the Basic Multilingual Plane fit in one char; others, including many emoji, use two char values called a surrogate pair. Text processing that must be correct for all characters should work with code points.
What happens when an int exceeds Integer.MAX_VALUE?
It wraps around to negative values without an exception, because of two's complement arithmetic. Use long, or Math.addExact and related methods to throw ArithmeticException on overflow.
How should money be represented in a Java system?
Never as float or double, because binary floating point cannot represent decimal fractions exactly and errors accumulate. Use BigDecimal with explicit scale and rounding mode, or a long count of the smallest currency unit, together with the currency. Many teams wrap this in a Money value type.
Why does NaN == NaN return false, and how do you test for NaN?
IEEE 754 defines NaN as unordered and unequal to everything, including itself. Test with Double.isNaN(x). Note that Double.equals treats NaN as equal to NaN, so boxed and primitive comparisons behave differently.
When would you choose float over double, or short over int, in a design?
Only when memory or bandwidth for very large arrays dominates and the reduced range or precision is acceptable — for example large numeric buffers, embeddings or sensor data. For ordinary fields and calculations, int, long and double (or BigDecimal for money) are clearer and not slower.
What type does a numeric literal have, and when do you need a suffix?
An integer literal such as 42 is an int, and a decimal literal such as 3.14 or 1e-3 is a double. A literal that does not fit in an int needs the L suffix to be a long, and a literal meant as a float needs f, because a double does not convert to float implicitly. Hex (0x2A), binary (0b101010) and underscores (1_000_000) change only how the value is written. An upper-case L is preferred because a lower-case l looks like the digit 1.
What does this program print?
public class PrimQuiz {
public static void main(String[] args) {
System.out.println(1 / 3 + " " + 1 / 3.0 + " " + 1 / 3f);
System.out.println(0.1f == 0.1);
System.out.println(Long.MAX_VALUE + 1 == Long.MIN_VALUE);
char c = 65;
System.out.println(c);
}
}It prints 0 0.3333333333333333 0.33333334, false, true, A. 1 / 3 is integer division, 0; with a double or float operand the division is done in that type, with 16 or 8 significant digits. 0.1f widened to double is 0.10000000149011612, not the double nearest 0.1, so the comparison is false. Long.MAX_VALUE + 1 wraps to Long.MIN_VALUE like every integer type, and a char initialised with 65 prints as the character A.
What does this program print?
public class FloatQuiz {
public static void main(String[] args) {
float f = 16_777_217;
System.out.println(f == 16_777_216f);
int id = 123_456_789;
float g = id;
System.out.println((int) g);
}
}It prints true and 123456792. A float has a 24-bit significand, so above 2^24 = 16,777,216 not every integer can be represented: 16,777,217 is rounded to 16,777,216, and 123,456,789 becomes 123,456,792. The conversion from int to float is a widening conversion and needs no cast, yet it loses information, which is why storing identifiers or counts in float is a bug.
How many bytes does a boolean use, and how does the JVM compute with byte and short?
The JLS does not say. HotSpot holds a boolean, byte, char or short as a 32-bit int in local variables and on the operand stack, and computes with int instructions; in fields and arrays it stores them at their natural size, one byte for a boolean or byte and two for char and short (Figure 4), though field layout may add padding. So small types save memory in large arrays but never make arithmetic faster.
A legacy service stores event timestamps as int seconds since 1970. What happens, when, and how do you migrate?
A signed 32-bit count of seconds overflows at 03:14:07 UTC on 19 January 2038; the next second is stored as a large negative number, a date in December 1901, and sorting, expiry and retention logic break. Future dates such as 20-year contract ends fail already today. Migrate to long milliseconds or Instant in code and to BIGINT or a timestamp type in the database: add the new column, write both, backfill, switch readers, then drop the old column, and test with dates beyond 2038.
What numeric type standards would you set for a platform of many services and clients?
One canonical type per concept, written into the API and data guidelines: long or UUID for identifiers, serialised as strings for JavaScript clients; money as an amount with a currency, BigDecimal or minor units in long, never double; java.time types for instants and durations, with ISO 8601 on the wire; long for counts and sizes; double only for measurements, with the unit in the name. Back the standard with schema linting for OpenAPI and database migrations, static-analysis rules against double money fields, and shared value types so teams do not reinvent them.
A protocol defines unsigned 64-bit fields, but Java has no unsigned types. What are the options?
Store the bits in a long and use the unsigned helpers, Long.compareUnsigned, divideUnsigned, remainderUnsigned and toUnsignedString: it is compact and fast, but every comparison and division must use the helper, and a forgotten one gives wrong answers for values above 2^63. BigInteger is always correct and readable but allocates and is far slower. A small value type that wraps the long and exposes only unsigned operations combines the speed of the first with the safety of the second, and is what most protocol libraries do; addition, subtraction and multiplication need no helper, because two's complement gives the same bits for signed and unsigned.
Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- Eight primitives with fixed sizes on every platform.
- Integers are two's complement and wrap silently on overflow.
- float/double are binary floating point: never for money, never compared with ==.
- char is a UTF-16 code unit, not always a whole character; boolean is not a number.