Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
Java's data types for the OCP 21 exam: the eight primitives and their ranges, numeric literals in four bases, underscore rules, primitives versus references, wrapper classes with valueOf and parseXxx, and text blocks with incidental whitespace and escapes.
kvi5hnuCode Sprout team member13 min readOn this page
Every value in a Java program is either a primitive or a reference to an object. The exam tests the eight primitive types, how literals are written, which assignments compile, how wrapper classes convert between strings and numbers, and how text blocks turn source code into a String. Most of these questions are about what compiles. Read every literal carefully.
The eight primitive types
A primitive holds a single value directly in the variable: a number, a character or a truth value. It isn't an object and has no methods.
| Type | Kind | Size | Range | Field default | Literal example |
|---|---|---|---|---|---|
boolean | true / false | not specified | true, false | false | true |
byte | integer | 8 bits | −128 to 127 | 0 | 7 |
short | integer | 16 bits | −32,768 to 32,767 | 0 | 300 |
char | Unicode code unit | 16 bits | 0 to 65,535 | '\u0000' | 'a' |
int | integer | 32 bits | about ±2.1 billion | 0 | 42 |
long | integer | 64 bits | about ±9.2 × 10¹⁸ | 0L | 42L |
float | floating point | 32 bits | about ±3.4 × 10³⁸ | 0.0f | 1.5f |
double | floating point | 64 bits | about ±1.8 × 10³⁰⁸ | 0.0 | 1.5 |
What the exam expects you to know:
byte,short,intandlongare signed whole-number types. Each is twice the size of the previous one. One bit is used for the sign, so abyteruns from −128 to 127, not 0 to 255. Know thebyteandshortranges. Bigger limits are given in the question if they matter.charis the only unsigned numeric type. It's a 16-bit number that represents a UTF-16 code unit.shortandcharare both 16 bits but cover different ranges, so a cast is needed in each direction.floatanddoublehold fractions.doubleis the default for decimal literals.- The size of
booleanis not defined by the language. It depends on the JVM. Stringis not a primitive, even though it has its own literals and the+operator. It's a class injava.lang.
Numeric literals
A literal is a value written directly in code. Its type follows a few rules.
Whole numbers are int by default. A number too big for an int doesn't compile, even when the variable is a long:
long tooBig = 3000000000; // DOES NOT COMPILE: integer number too large
long fine = 3000000000L; // L makes it a long literal
Lowercase l is legal but looks like the digit 1, so always use L.
Decimal numbers are double by default. A float variable needs an f or F suffix:
float a = 1.5; // DOES NOT COMPILE: possible lossy conversion from double to float
float b = 1.5f; // OK
float c = 1; // OK: an int widens to float
double d = 1.5d; // OK: d or D is allowed but optional
double e = 2e3; // OK: scientific notation, 2000.0
double f = .5; // OK: 0.5
double g = 5.; // OK: 5.0
Small integer constants fit into smaller types. byte b = 10;, short s = 300; and char c = 65; all compile, because the compiler checks that the constant value fits. byte b = 128;, short s = 32768; and char c = -1; don't. This works only for constant values, and the chapter on operators shows where it stops.
Two boundary cases look wrong but compile: int min = -2147483648; (the minus sign applies to a literal that is allowed only in this position) and int all = 0xFFFFFFFF; (a hex literal can fill all 32 bits, and its value is −1).
Four bases
| Base | Prefix | Digits | Example | Value |
|---|---|---|---|---|
| Decimal | none | 0–9 | 42 | 42 |
| Octal | 0 | 0–7 | 052 | 42 |
| Hexadecimal | 0x or 0X | 0–9, a–f, A–F (any case) | 0x2A, 0x2a | 42 |
| Binary | 0b or 0B | 0–1 | 0b101010 | 42 |
A leading zero makes a whole number octal, so 08 and 09 don't compile (illegal digit in an octal literal). That rule is only for integers: 09.5 is a perfectly good double. Expect at least one question that asks which literals are valid.
Underscores in numbers
Underscores make long numbers readable, as in 1_000_000. They're ignored by the compiler and allowed between digits only:
| Literal | Compiles? | Why |
|---|---|---|
1_000_000 | Yes | Between digits |
1__0 | Yes | Several in a row are allowed, just ugly |
1_00_0.0_0 | Yes | Between digits on both sides of the point |
0_7 | Yes | An octal literal; the leading 0 counts as a digit |
_1000 | No | At the start, it's an identifier, not a number |
1000_ | No | At the end |
1000_.0, 1000._0 | No | Next to the decimal point |
0x_FF, 0b_1 | No | Right after a 0x or 0b prefix |
100_L, 1.5_f | No | Right before a type suffix |
1e_3 | No | Next to the exponent e |
char literals
A char literal uses single quotes: 'a', '7', '\n', '\''. It can also be a Unicode escape such as '\u0041', which is the same character as 'A'. Because char is a number, 'A' + 2 is the int 67. Casting it back gives 'C', as in (char) ('A' + 2). Double quotes always make a String, so 'ab' doesn't compile and "a" isn't a char.
Reference types
A reference type is any class, interface, record, enum or array type. A reference variable doesn't hold the object. It holds a way of reaching the object, conceptually a pointer, although Java never shows you a memory address:
String greeting; // a reference that can point to a String
greeting = "How are you?"; // now it points to a String object
String same = greeting; // a second reference to the SAME object
Keep the two ideas apart:
- A reference has a name and a type. It can be copied, assigned, passed to methods and returned. All references are the same size, whatever they point to.
- An object lives on the heap, has no name and is reached only through references. Objects, not references, are garbage collected.
Primitives versus references
| Primitive | Reference | |
|---|---|---|
| Holds | the value itself | a way to reach an object |
| Type name | lowercase keyword (int) | by convention starts uppercase (String) |
| Can call methods | No: int n; n.length() doesn't compile | Yes, if it isn't null |
Can be null | No: int x = null; doesn't compile | Yes |
| Field default | 0, 0.0, false, '\u0000' | null |
To represent "no number", use a wrapper type, as in Integer count = null;.
Wrapper classes
Each primitive has a wrapper class in java.lang, an object that holds one primitive value:
| Primitive | Wrapper | Extends Number? | Creating one |
|---|---|---|---|
boolean | Boolean | No | Boolean.valueOf(true) |
byte | Byte | Yes | Byte.valueOf((byte) 1) |
short | Short | Yes | Short.valueOf((short) 1) |
int | Integer | Yes | Integer.valueOf(1) |
long | Long | Yes | Long.valueOf(1) |
float | Float | Yes | Float.valueOf(1.0f) |
double | Double | Yes | Double.valueOf(1.0) |
char | Character | No | Character.valueOf('c') |
Two names differ from their primitives: Integer and Character. The exam may use Int or Char as wrong answers.
From a String: parseXxx versus valueOf
int primitive = Integer.parseInt("123"); // returns int
Integer wrapper = Integer.valueOf("123"); // returns Integer
The rule: parseXxx returns a primitive, valueOf returns a wrapper. Thanks to autoboxing (the methods chapter) you can usually assign either result to either type, so watch for questions where the difference matters, such as calling a method on the result.
What goes wrong:
Integer.parseInt("12.5"),Integer.valueOf("five")andInteger.valueOf(" 5")throwNumberFormatException. The integer parsers accept an optional+or-sign, but no spaces and no decimal point.Integer.parseInt(null)throwsNumberFormatExceptiontoo, butDouble.valueOf(null)throwsNullPointerException.Double.valueOftrims surrounding spaces, soDouble.valueOf(" 1.5 ")works.Boolean.valueOf(s)never throws. It returnstruewhensequals"true"ignoring case, andfalsefor everything else, including"yes","1"andnull.
The integer wrappers also accept a radix (base): Integer.valueOf("ff", 16) is 255, Integer.parseInt("11", 2) is 3. Letters are case-insensitive. A digit that's invalid for the base, such as Integer.valueOf("g", 16), throws NumberFormatException.
From a wrapper: the xxxValue() methods
Every Number subclass offers byteValue(), shortValue(), intValue(), longValue(), floatValue() and doubleValue(). Boolean has booleanValue() and Character has charValue(). Conversions can lose information:
Double d = Double.valueOf("300.75");
d.intValue(); // 300 (fraction dropped)
d.byteValue(); // 44 (300 doesn't fit in a byte; only the low 8 bits are kept)
Wrappers also have static helpers such as Integer.max(a, b), Integer.min(a, b) and Integer.sum(a, b). You don't need to memorize them. Assume any helper shown in a question exists.
Text blocks
A text block (final since Java 15) is a String literal that spans several lines. Without one, a quote and a line break need escapes:
String old = "\"Java\" basics\n by the team";
String tb = """
"Java" basics
by the team""";
Both produce the same String. A text block is just another way to write a String literal, so every String method works on it, and it can go anywhere a String can: in a variable, as a method argument or in a + expression.
The rules
- The opening
"""must be followed by a line break.String s = """abc""";doesn't compile ("illegal text block open delimiter sequence, missing line terminator"). - The content starts on the next line, and the closing
"""can end the last content line or sit on a line of its own. - If the closing
"""is on its own line, the string ends with a newline. - Quotes need no escaping, except that three in a row must be broken up, as in
\""". - Trailing spaces at the end of each line are removed.
javac -Xlintwarns about them.
Incidental and essential whitespace
The compiler removes the indentation that only exists to line the block up with your code. Find the leftmost non-blank character over all the content lines and the closing """ line. Everything left of that column is incidental whitespace and is stripped. Everything right of it is essential whitespace and stays.

String tri = """
*
* *
* * *
""";
System.out.print(tri);
This prints three lines, *, * * and * * *, each followed by a newline. Moving the closing """ left adds essential spaces to every line. Moving it to the right of the content has no effect, because the closing line then counts only up to the content's own left edge.
Escapes in text blocks
| You write | In a "..." string | In a text block |
|---|---|---|
" | ends the string | a quote |
\" | a quote | a quote |
""" | not possible | ends the text block |
\""" | not possible | three quotes |
| space at end of a line | n/a | removed |
\s | one space | one space, and stops trailing-space removal on that line |
\ at end of a line | doesn't compile | joins the next line (no newline) |
\n, \t | newline, tab | newline, tab |
Examples to check your understanding:
String a = """
doe \
deer"""; // "doe deer": one line, the \ removed the newline
String b = """
doe \n
deer
"""; // "doe \n\ndeer\n": the explicit \n plus the real line break
String c = """
keep\s
"""; // "keep \n": \s keeps the space
Text blocks often pair with formatted(...), which works like String.format:
String line = """
Total: %d
""".formatted(698); // "Total: 698\n"
The methods stripIndent() and translateEscapes() apply the same processing to an ordinary string at runtime.
What's current
- String templates were previewed in Java 21 and 22 and then withdrawn. They aren't part of Java.
- Primitive types in patterns are a preview from Java 23 on and aren't on either exam. Primitive types, literals, wrappers and text blocks are otherwise unchanged through Java 25.
Exam traps from this article
A complete example
public class Solution {
public static void main(String[] args) {
// 1. Ranges come from the wrapper classes' MIN_VALUE / MAX_VALUE constants.
System.out.println("byte " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE);
System.out.println("short " + Short.MIN_VALUE + " to " + Short.MAX_VALUE);
System.out.println("char " + (int) Character.MIN_VALUE + " to " + (int) Character.MAX_VALUE);
System.out.println("int " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);
System.out.println("long " + Long.MIN_VALUE + " to " + Long.MAX_VALUE);
// 2. The same number, 42, written in four bases, plus underscores for readability.
int decimal = 42, octal = 052, hex = 0x2A, binary = 0b10_1010;
long big = 3_000_000_000L; // needs L: too large for an int
float price = 9.99f; // needs f: 9.99 alone is a double
System.out.println(decimal + " " + octal + " " + hex + " " + binary + " " + big + " " + price);
// 3. char is an unsigned 16-bit number.
char letter = 'A';
char fromNumber = 66; // an int constant that fits is allowed
System.out.println(letter + "" + fromNumber + " " + (int) letter + " " + (char) (letter + 2));
// 4. Strings to numbers: parseXxx gives a primitive, valueOf gives a wrapper.
int parsed = Integer.parseInt("123");
Integer wrapped = Integer.valueOf("123");
System.out.println(parsed + 1 + " " + wrapped.equals(parsed) + " " + Integer.valueOf("ff", 16));
System.out.println(Boolean.valueOf("TRUE") + " " + Boolean.valueOf("yes"));
try {
Integer.parseInt("12.5");
} catch (NumberFormatException e) {
System.out.println("NumberFormatException: " + e.getMessage());
}
// 5. Number's xxxValue() methods convert, possibly losing information.
Double d = Double.valueOf("300.75");
System.out.println(d.intValue() + " " + d.byteValue() + " " + d.longValue());
// 6. A text block: incidental indentation removed, essential spaces kept.
String receipt = """
Item Qty
"Tea" 2 \
(green)
Total: %d
""".formatted(2 * 349);
System.out.print(receipt);
}
}
Output:
byte -128 to 127
short -32768 to 32767
char 0 to 65535
int -2147483648 to 2147483647
long -9223372036854775808 to 9223372036854775807
42 42 42 42 3000000000 9.99
AB 65 C
124 true 255
true false
NumberFormatException: For input string: "12.5"
300 44 300
Item Qty
"Tea" 2 (green)
Total: 698
Points to notice:
letter + "" + fromNumberstarts with acharbut the""makes it string concatenation, so it printsABrather than the sum 131.parsed + 1 + " "adds first (124) and concatenates afterwards, because+is evaluated left to right.- In the text block, the closing
"""sets the margin, so the first two lines keep two spaces. The\joins(green)onto the"Tea"line.
Common questions
Why does long x = 3000000000; fail when a long can hold that value?
Because the literal itself is an int, and 3,000,000,000 is too large for an int. The compiler rejects the literal before thinking about the variable. Adding L makes it a long literal.
Is char a number or a character?
Both. It's an unsigned 16-bit integer that Java prints as a character. You can do arithmetic on it, and the result is an int.
Why is boolean not 1 bit?
The JVM specification leaves its size to the implementation. In practice a boolean field usually takes a byte, and boolean arrays use a byte per element. You can't do arithmetic with boolean, and it can't be cast to or from a number.
When should I use parseInt versus valueOf?
Use parseInt when you want an int to compute with, and valueOf when you need an Integer object, for example to store in a collection. Both reject the same bad input.
Does a text block create a different kind of string?
No. The compiler turns it into an ordinary String constant. """\n hi""".equals("hi") is true, and identical text blocks and string literals refer to the same pooled object.
Can a text block be empty?
Yes. """ followed by a line containing only """ is the empty string "".
Summary
- Eight primitives:
boolean,byte,short,char,int,long,float,double. Integer types are signed exceptchar.Stringis a class. - Whole-number literals are
intand decimal literals aredoubleunless they end inLorf. A literal that doesn't fit its type doesn't compile. - Prefixes:
0for octal,0xfor hex,0bfor binary. Underscores go only between digits. - A primitive holds its value, can't be
nulland has no methods. A reference points to an object on the heap. - Wrappers:
parseXxxreturns a primitive,valueOfreturns a wrapper, invalid numbers throwNumberFormatException, andBoolean.valueOfnever throws. Wrapper constructors are deprecated for removal. - Text blocks start with
"""and a line break. The leftmost non-blank column decides the indentation that is stripped, trailing spaces are removed,\skeeps a space and\at a line end joins lines.
Practice quiz
Test yourself with the primitive types, literals and wrappers quiz: 10 exam-style questions with explanations.
Previous: Creating Objects in Java: Constructors, Instance Initializers and Order of Initialization (OCP 21)
Next: Declaring and Initializing Java Variables: Identifiers, Defaults and var (OCP 21)
Related reading
- Java Building Blocks: JDK, JVM, Class Structure and the main Method (OCP 21)
- Java Sealed Classes and Interfaces: Controlling Inheritance
- The Java String API, Code Points, StringBuilder and Text Blocks
- Java Packages and Imports: Wildcards, Conflicts, Compiling and the Class Path (OCP 21)
- FFM Memory Layouts: Structs, Unions, Sequences and Var Handles

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.