Topic 1.2 — Variables and Data Types

Goal: declare variables, choose appropriate primitive data types, assign values, and understand what it means for a variable to “store” data.

The big idea

A variable is a named storage location. It holds a value you can use later. In Java, every variable has a type, and the type controls what values it can hold and what operations make sense.

Think: type = rules. Wrong type → compile-time error or unexpected results.

Core vocabulary

  • Variable: a name that refers to stored data.
  • Data type: defines what kind of values a variable can store.
  • Primitive type: basic built-in types like int, double, boolean.
  • Declare: create a variable by giving it a type and name.
  • Initialize: give a variable its first value.
  • Assignment: store a new value using =.

Declaring variables (starter syntax)

Pattern:

type variableName;
        // or
type variableName = value;

Examples:

int score = 0;
double price = 2.50;
boolean isDone = false;

Naming rules (what Java allows)

  • Must start with a letter, _, or $.
  • Can contain letters and digits after the first character.
  • Case-sensitive: score and Score are different.
  • Use meaningful names: totalPoints is better than x.

Common primitive types (Unit 1 focus)

int — integers

Whole numbers (no decimals).

int apples = 12;
int change = -3;

double — decimals

Numbers with fractional parts.

double gpa = 3.75;
double taxRate = 0.0825;

boolean — true/false

Used for decisions (more in Unit 2).

boolean hasTicket = true;
boolean isEmpty = false;

char — one character

Single character in single quotes.

char grade = 'A';
char space = ' ';

Assignment vs. equality

  • = stores a value (assignment).
  • == compares values (you’ll use this later).
int x = 5;   // assignment
// x == 5;   // comparison (not used like this yet)

Updating a variable (re-assign)

int score = 0;
score = 7;
score = score + 3;

Read score = score + 3 as: “take the old score, add 3, store it back.”

Common mistakes

  • Using a variable before it’s initialized → compile-time error.
  • Putting a decimal into an int → type mismatch error.
int a;
System.out.println(a); // error: might not have been initialized

int b = 3.5;           // error: incompatible types

Quick self-check

  1. What are the two parts of a variable declaration?
  2. Best type: number of students in a class?
  3. Best type: price of a sandwich?
  4. What does it mean to initialize a variable?
  5. Explain: x = x + 1

← Back to Unit 1 topics