01 / 21
x = 5

Variables &
Data Types

Learn how Java stores information using variables, and master the primitive data types that form the foundation of every AP Computer Science A program.

AP Computer Science A

What is a Variable?

A variable is a named storage location in memory that holds a value. Think of it as a labeled box: the label is the variable's name, and the contents are its current value.

42 score int 3.14 gpa double 'A' grade char

Declaring and Initializing

Declaration creates the variable. Initialization gives it a first value. You can do both in one statement or separately.

// Declaration only int age; // Initialization age = 17; // Declaration + initialization in one step double temperature = 98.6;

Why Data Types Matter

Java is a statically typed language: the compiler checks types before your code runs. Choosing the right type affects memory usage, precision, and allowed operations.

Memory
An int uses 4 bytes; a double uses 8 bytes. Picking the right size avoids waste.
Safety
The compiler catches mistakes like adding a boolean to an int before the program runs.
Precision
Using int for currency loses cents. Using double preserves decimal places.

Java's Primitive Data Types

Java has 8 primitive types. The AP CSA exam focuses on three: int, double, and boolean.

Primitive Type Family Tree Numeric Types Integer Types byte short int ★ long Floating-Point float double ★ boolean ★ char ★ = AP CSA Focus

The int Type: Whole Numbers

An int stores a 32-bit signed integer. It can hold values from \( -2^{31} \) to \( 2^{31} - 1 \), which is roughly -2.1 billion to +2.1 billion.

int students = 30; int year = 2025; int negativeVal = -150;

The double Type: Decimals

A double stores a 64-bit floating-point number. Use it whenever you need decimal precision: measurements, averages, scientific calculations.

double price = 19.99; double pi = 3.14159; double result = 7.0 / 2.0; // 3.5

The boolean Type: True or False

A boolean can only hold two values: true or false. Booleans drive conditions, loops, and logical expressions.

boolean isRaining = true; boolean passed = score >= 60; if (passed) { System.out.println("Congratulations!"); }

Primitive vs. Reference Types

Java has two categories of types. Primitive types store the value directly. Reference types store a pointer to an object in memory.

Primitive score 42 Value stored directly done true Reference name 0x3A7F Points to object nums 0x9B02 int, double, boolean String, arrays, objects

Two collaborators work on one shared model

Two collaborators adjust one blue articulated model while a second model stands apart.Java assignment copies a value. For primitive variables this is the primitive value; for object variables it is a reference to an object.

Assignment copies a value

Primitive variables x and y separate after reassignment; String references a and b point to different immutable strings.After x is changed to 9, y keeps its copied value of 42. For String variables, assignment copies a reference: reassigning a to "world" leaves b referring to the unchanged "hello" object.

Naming Variables Correctly

1
Start with a letter, underscore, or dollar sign: score, _count, $total are valid.
2
Cannot start with a digit: 2ndPlace is illegal. Use secondPlace instead.
3
No spaces or special characters: my score and total# are invalid.
4
Use camelCase by convention: totalScore, isGameOver, maxValue.
5
Cannot be a reserved word: int, class, void cannot be variable names.

Choosing the Right Type

1
Identify the data: What kind of value will the variable hold? A count? A measurement? A yes/no flag?
2
Need decimals? Use double. Whole numbers only? Use int.
3
True/false condition? Use boolean. Text? Use String (reference type).
4
Choose a descriptive name in camelCase. Avoid single letters except for loop counters.
5
Declare and initialize in one statement whenever possible for clarity and safety.

Example 1: Basic Declarations

A student tracker program needs to store a student's name, age, GPA, and whether they are enrolled.

String name = "Alice"; // reference type int age = 16; // whole number double gpa = 3.85; // decimal number boolean isEnrolled = true; // yes/no flag

Example 2: Integer Division Trap

What does Java compute for each expression?

int a = 7 / 2; // a = 3 (truncated, not rounded) double b = 7 / 2; // b = 3.0 (int / int = int, then stored as double) double c = 7.0 / 2; // c = 3.5 (double / int = double) double d = (double) 7 / 2; // d = 3.5 (cast forces double division)

Example 3: Type Casting

Widening (int to double) happens automatically. Narrowing (double to int) requires an explicit cast and truncates the decimal.

// Widening: automatic, safe int x = 5; double y = x; // y = 5.0 (no cast needed) // Narrowing: explicit cast required double pi = 3.99; int approx = (int) pi; // approx = 3 (truncated, NOT rounded)
int auto double double cast int Widening (safe) Narrowing (lossy)

Common Mistakes to Avoid

✕ Uninitialized Variables
Using a local variable before assigning a value causes a compile error. Always initialize.
✕ Integer Division Surprise
Writing \(5 / 3\) expecting \(1.667\) but getting \(1\). At least one operand must be a double.
✕ Comparing Doubles with ==
Floating-point imprecision means \(0.1 + 0.2 == 0.3\) is false. Use a tolerance check instead.
✕ Wrong Type for the Job
Storing a grade average in an int loses decimal precision. Use double for any non-whole value.

Summary Comparison

Feature int double boolean
Stores Whole numbers Decimal numbers true / false
Size 32 bits (4 bytes) 64 bits (8 bytes) 1 bit (JVM varies)
Default Value (fields) 0 0.0 false
Example int n = 10; double d = 2.5; boolean b = true;
Division Truncates (\(7/2 = 3\)) Preserves (\(7.0/2 = 3.5\)) N/A

Question 1 of 5

What is the value of result after this code runs?

int result = 13 / 5;

Question 2 of 5

Which of the following is a valid Java variable name?

Question 3 of 5

What is the output of the following code?

double x = 7 / 2;
System.out.println(x);

Question 4 of 5

What is the value of y after this code executes?

double pi = 3.99;
int y = (int) pi;

Question 5 of 5

Which data type should you use to store whether a user has accepted the terms of service?