JAVA • SYNTAX AND CORE TYPES

Primitive Types — Work with int, double, boolean, and char primitives

Master the four essential building blocks that store numbers, decisions, and characters in every Java program.

Historical Context & Motivation

Every computer program needs a way to store and manipulate data, whether that data represents a player's score, a temperature reading, a yes-or-no decision, or a letter of the alphabet. In the earliest days of programming, developers worked directly with raw binary values in memory, which was error-prone and confusing. Programming languages evolved to offer data types — labels that tell the computer how to interpret a chunk of memory. When James Gosling and his team at Sun Microsystems designed Java in the mid-1990s, they made a deliberate choice: Java would include a small set of primitive types that are simple, fast, and predictable across every platform.

1972
C Language Introduces Typed Variables
Dennis Ritchie's C language popularized the idea of declaring a variable's type (like int and char) before using it, giving the compiler crucial information about memory layout.
1985
C++ Adds Object-Oriented Layers
Bjarne Stroustrup extended C with classes and objects, but kept primitive types for performance. This dual approach — primitives for speed, objects for complexity — influenced Java's design.
1995
Java 1.0 Released
Sun Microsystems released Java with exactly eight primitive types. The language guaranteed that int would always be 32 bits, double always 64 bits — regardless of the operating system.
2004
Java 5 Adds Autoboxing
Java 5 introduced automatic conversion between primitives and their object wrappers (e.g., int ↔ Integer), making it easier to use primitives with collections and generics.

The central question this lesson addresses is straightforward but essential: How do you store a whole number, a decimal, a true/false value, or a single character in Java? Understanding the four most commonly used primitive types — int, double, boolean, and char — gives you the vocabulary to write virtually any Java program.

Core Principles & Definitions

A primitive type in Java is a data type built directly into the language. Unlike objects, primitives do not have methods or properties — they are raw values stored efficiently in memory. Java has eight primitives in total, but the four you will use most often are int, double, boolean, and char. Each one is designed for a specific category of data, and choosing the right type matters for both correctness and performance.

1

int — Whole Numbers

Stores integers from −2,147,483,648 to 2,147,483,647 using 32 bits (4 bytes). Perfect for counters, scores, and indexes.
2

double — Decimal Numbers

Stores floating-point numbers with up to about 15 digits of precision using 64 bits (8 bytes). Ideal for measurements, grades, and scientific data.
3

boolean — True or False

Holds exactly one of two values: true or false. Used for conditions, flags, and logical decisions throughout your code.
4

char — Single Character

Stores one Unicode character (like 'A', '7', or '★') using 16 bits (2 bytes). Always enclosed in single quotes.
✦ KEY TAKEAWAY
Think of primitive types like different-shaped containers in a kitchen. An int is a measuring cup that only holds whole scoops. A double is a graduated cylinder that measures precise amounts. A boolean is a light switch — on or off, nothing in between. A char is a single letter tile from a board game. You pick the container that matches the kind of data you need to store.

Visual Explanation — Memory Layout

When you declare a variable like int score = 95;, Java reserves a specific number of bytes in memory and stores the value there. The diagram below shows how each of the four primitive types occupies memory, along with example values and their binary (bit-level) representations.

Each row shows a primitive type, its memory footprint, an example value, and how that value looks as hexadecimal bytes in memory. Notice how double takes twice as much space as int because it needs room for the decimal point and extra precision.

The key insight from the diagram is that Java commits a fixed amount of memory for each primitive type at compile time. An int always uses 4 bytes whether it stores the number 0 or the number 2,000,000. This predictability is what makes primitives fast: the JVM never has to guess how much space to allocate.

How Declarations and Assignments Work

Every primitive variable in Java follows the same declaration pattern. You write the type first, then the variable name, and optionally assign an initial value with the = operator. The semicolon at the end tells Java the statement is complete. Let's examine the syntax for each type.

DECLARATION SYNTAX
type variableName = value;
type — one of the primitive keywords (int, double, boolean, char). variableName — a valid identifier starting with a letter. value — a literal matching the type (e.g., 42, 3.14, true, 'A').

int Declarations

An int literal is simply a whole number with no decimal point. You can use underscores in large numbers for readability. For example, int population = 1_000_000; is perfectly valid and stores the value one million. Integer arithmetic uses operators like +, -, *, / (integer division), and % (remainder). A critical detail: dividing two ints always produces an int, which means 7 / 2 evaluates to 3, not 3.5.

double Declarations

A double literal includes a decimal point, like double gpa = 3.85;. When you mix int and double in an expression, Java automatically promotes the int to a double before computing the result. So 7.0 / 2 yields 3.5 because the 2 is promoted to 2.0 first. Be aware that doubles can produce tiny rounding errors — for instance, 0.1 + 0.2 returns 0.30000000000000004 due to how binary floating-point works.

boolean Declarations

A boolean can only hold true or false. These values are keywords in Java and are case-sensitive — True with a capital T will cause a compiler error. Booleans are the backbone of decision-making: every if statement and while loop evaluates a boolean expression. For example, boolean isRaining = true; and later if (isRaining) { ... }.

char Declarations

A char stores exactly one character, enclosed in single quotes — not double quotes. Writing char grade = 'A'; is correct, but char grade = "A"; will not compile because double quotes create a String, which is an object, not a primitive. Under the hood, each char is a 16-bit Unicode number, so you can do arithmetic with chars: 'A' + 1 evaluates to 66 (the integer code for 'B').

Detailed Breakdown — Ranges, Defaults, and Casting

Summary of the four key primitive types in Java
TypeSizeRange / ValuesDefault ValueExample Literal
int32 bits (4 bytes)−2,147,483,648 to 2,147,483,647042
double64 bits (8 bytes)±4.9 × 10⁻³²⁴ to ±1.8 × 10³⁰⁸0.03.14
boolean1 bit (logical)true or falsefalsetrue
char16 bits (2 bytes)Unicode 0 to 65,535'\u0000''Z'
This diagram shows the automatic (widening) promotion path from char → int → double, and how narrowing requires an explicit cast (parenthesized type). Note that boolean is isolated — it cannot be cast to or from any numeric type.

When you assign a smaller type to a larger type — for instance, storing an int into a double — Java performs widening conversion automatically with no risk of data loss. Going the other direction is called narrowing conversion and requires you to write a cast — the target type in parentheses — because the decimal portion gets chopped off, not rounded. The value 9.78 cast to int becomes 9, not 10.

Worked Example — Building a Simple Grade Calculator

Let's trace through a short Java program that uses all four primitive types to calculate a student's final letter grade. We'll go step by step, noting the type of each variable and what value it holds after each statement executes.

Grade Calculator Using Primitives
1
Step 1 — Declare int variables for scoresWe declare two int variables to hold exam scores: int exam1 = 88; and int exam2 = 94;. Both are whole numbers, so int is the correct type.
exam1 = 88, exam2 = 94
2
Step 2 — Calculate the average as a doubleWe need a decimal-capable type for the average. We write double average = (exam1 + exam2) / 2.0;. The 2.0 is critical — it forces Java to use double division. If we wrote / 2 instead, integer division would give us 91 instead of 91.0. Here, (88 + 94) / 2.0 = 182 / 2.0 = 91.0.
average = 91.0
3
Step 3 — Determine a boolean pass/fail flagWe use a boolean to record whether the student passed: boolean passed = average >= 60.0;. Since 91.0 ≥ 60.0 is true, passed stores true.
passed = true
4
Step 4 — Assign a char letter gradeFinally, we store the letter grade in a char: char letterGrade = 'A'; (since 91.0 is in the A range of 90–100). Notice the single quotes around 'A' — this is required for char literals.
letterGrade = 'A'
5
Step 5 — Print the resultsWe output: System.out.println(letterGrade + ": " + average + " — Passed: " + passed);. Java automatically converts each primitive to its String representation when concatenated with +.
Output: A: 91.0 — Passed: true

Primitives vs. Wrapper Objects

Java provides an object-based "wrapper" class for each primitive type: Integer for int, Double for double, Boolean for boolean, and Character for char. Understanding when to use each is a common point of confusion for new programmers. The table below highlights the key differences.

Primitives vs. their wrapper-class counterparts
FeaturePrimitive (e.g., int)Wrapper (e.g., Integer)
StoresThe actual value directlyA reference to an object on the heap
SpeedFasterSlower due to object overhead
Can be null?No — always has a valueYes — can be null
Works in ArrayList?No — collections require objectsYes
Has methods?NoYes (e.g., Integer.parseInt())
Default value0 / 0.0 / false / '\u0000'null
✦ KEY TAKEAWAY
Use primitives by default for everyday variables like loop counters, scores, and flags. Think of a primitive like cash in your pocket — you can spend it instantly. A wrapper object is like a check: it holds the same amount, but you have to process it first, which takes extra time. Only reach for wrappers when you need features like null values or storing data in an ArrayList.

Connections to Advanced Java Topics

The four primitives you have learned form the foundation for nearly everything else in Java. As you advance, you will encounter situations where primitives connect to more complex language features. The table below previews how each type extends into topics you will study soon.

How primitive type concepts connect to advanced Java topics
Primitive ConceptAdvanced ConnectionWhat You'll Learn
int variablesArrays and loopsStoring many ints in an int[] array and iterating with a for loop
double precisionBigDecimal classExact decimal math for currency and financial calculations without rounding errors
boolean logicControl flow and Boolean algebraCombining conditions with && (and), || (or), and ! (not)
char sequencesString classA String is essentially a sequence of chars with powerful methods for searching, splitting, and formatting
Type castingPolymorphism and inheritanceObject casting follows similar widening/narrowing rules when working with class hierarchies

Java also has four other primitive types you may encounter: byte (8 bits), short (16 bits), long (64 bits), and float (32-bit decimal). These exist for specialized use cases like saving memory in large arrays or interfacing with hardware, but int, double, boolean, and char cover the vast majority of everyday programming needs.

Practice Problems

PROBLEM 1 — CONCEPTUAL
A classmate writes int temperature = 98.6; and gets a compiler error. Explain why this fails and suggest two different ways to fix it.
PROBLEM 2 — BASIC CALCULATION
What value does each variable hold after these statements execute? int a = 17 / 5; int b = 17 % 5; double c = 17.0 / 5;
PROBLEM 3 — INTERMEDIATE
Consider the following code: char letter = 'C'; int code = letter; char next = (char)(letter + 1); What are the values of code and next? Why is the cast needed for next but not for code?
PROBLEM 4 — APPLIED
You are writing a program for a vending machine. A drink costs $1.75. The customer inserts $2.00. Write Java declarations for the price, the amount paid, and the change. Also declare a boolean that indicates whether the customer paid enough. Show the values of all four variables.
PROBLEM 5 — CRITICAL THINKING
A program tracks inventory with int itemCount = 2_147_483_647; (the maximum int value). When the code executes itemCount = itemCount + 1;, no error is thrown, but the value changes unexpectedly. What happens and why? What primitive type could prevent this issue?

Lesson Summary

Java's primitive types are the simplest and fastest way to store data. The int type holds whole numbers in 32 bits, the double type holds decimal numbers in 64 bits with about 15 digits of precision, the boolean type holds exactly true or false, and the char type holds a single Unicode character in 16 bits. Each variable is declared with the pattern type name = value;.

Key rules to remember: integer division truncates the decimal (7 / 2 = 3); widening conversions (int → double) happen automatically, while narrowing conversions (double → int) require an explicit cast; char literals use single quotes while Strings use double quotes; and boolean cannot be cast to or from any other type. Mastering these four primitives prepares you for arrays, control flow, and object-oriented programming in Java.

Varsity Tutors • Java • Primitive Types — Work with int, double, boolean, and char primitives