---
title: "Primitive Variable Declarations | FiveStudy"
description: "Type, name, value: the declaration promise, the four working types, and snapshot copies."
url: https://fivestudy.com/guides/primitive-variable-declarations
---

[AP Computer Science A](https://fivestudy.com/ap-computer-science-a) · Study guide

# Primitive Variable Declarations

[Figure: FiveStudy]

FiveStudy

AP® Computer Science A · Using Objects and Methods

AP® Computer Science A · Using Objects and Methods

# Primitive Variable *Declarations*

How to create variables that store numbers and true/false values: declaring and initializing them, choosing among int, double, and boolean, naming them well, and changing their values safely.

1. What a Variable Is 2. Declaring and Initializing 3. Choosing the Type 4. Naming Variables 5. Changing Values 6. Constants

Big Picture

A **variable** is a storage location that holds a value, which can change while the program is running. Every variable has a **name** and an associated **data type**. A variable of a primitive type holds a primitive value from that type. The three primitive types used here are `int` for integers, `double` for real numbers, and `boolean` for `true` or `false`. Declaring variables carefully, with the right type, a clear name, and an initial value, prevents a large share of beginner errors.

## 1 What a Variable Is

Think of a variable as a labelled box in the computer's memory. The label is the variable's **name**, the size and shape of the box are determined by its **type**, and the contents are its current **value**. A program can look in the box (use the value in an expression) or replace its contents (assign a new value).

Variables let programs remember information from one statement to the next: a running total, the number of attempts so far, whether a condition has been met. Without variables, every calculation would have to be written out from scratch with literal numbers, and programs could not respond to changing data.

The type is fixed when the variable is declared. A variable declared as an `int` can hold any integer in its range, but it can never hold a `double` or a `boolean`. Its value, on the other hand, can change as often as the program needs.

**Figure 1.** A variable is a named storage location whose value can change while the program runs. Each assignment replaces the previous value.

## 2 Declaring and Initializing

A **declaration** creates a variable by stating its type and its name, followed by a semicolon: `int age;`. The variable now exists, but it has no value yet. Assigning a value for the first time is called **initializing** the variable. The two steps can happen separately or in a single statement: `int age = 16;`.

Every variable must be assigned a value before it can be used in an expression. If the compiler cannot be sure that a variable has a value when it is read, it reports an error such as *variable might not have been initialized*. The simplest habit is to initialize each variable when you declare it, using a sensible starting value such as 0 for a running total or `false` for a flag that has not yet been set.

Where a variable is declared also matters. A variable declared inside a block of code, between a pair of braces, exists only within that block; once execution leaves the block, the variable is gone. For now, declare variables near the top of the block where they are first needed, so a reader can see each variable's type and starting value before it is used.

Several variables of the same type can be declared in one statement, separated by commas: `int wins = 0, losses = 0;`. One declaration per line is usually easier to read and comment, though.

**Figure 2.** A declaration states a variable's type and name. Adding `= value` initializes it in the same statement.

| Statement | What it does | Example |
| --- | --- | --- |
| Declaration | Creates a variable with a type and a name | `int age;` |
| Assignment | Stores a value in an existing variable | `age = 16;` |
| Declaration with initialization | Both at once | `int age = 16;` |
| Multiple declarations | Several variables of the same type | `int wins = 0, losses = 0;` |
| Constant | A variable that cannot be changed after it is set | `final double TAX_RATE = 0.08;` |

Worked Example 1 Declaring variables

### Variables for a Video Game Character

A game tracks a character's remaining lives (starting at 3), health as a percentage that can be fractional (starting at 100.0), whether the character holds a key (initially not), and the number of coins collected (starting at 0). Declare and initialize the variables, then print them.

Code

```
int lives = 3;
double health = 100.0;
boolean hasKey = false;
int coins = 0;
System.out.println(lives + " " + health + " " + hasKey + " " + coins);
```

Output

```
3 100.0 false 0
```

1. 1 **Choose types by meaning.** Lives and coins are counts (`int`), health can be fractional (`double`), and holding a key is yes/no (`boolean`).
2. 2 **Choose descriptive names.** `hasKey` reads naturally in a condition later: "if the character has the key."
3. 3 **Initialize when declaring.** Giving each variable its starting value in the declaration avoids using a variable before it has a value.

**Result:** The output is `3 100.0 false 0`. Notice that the `double` prints with a decimal point even when its value is a whole number.

Worked Example 2 Initialization

### Using a Variable Before It Has a Value

Explain why this code does not compile, and fix it.

Code that does not compile

```
int total;
total = total + 5;
System.out.println(total);
```

1. 1 **The problem.** `total` is declared but never given a value before line 2 tries to read it. Every variable must be assigned a value before it can be used in an expression.
2. 2 **The fix.** Initialize it first.

   Fixed

   ```
   int total = 0;
   total = total + 5;
   System.out.println(total);
   ```

   Output

   ```
   5
   ```

**Result:** The compiler reports that `total` might not have been initialized. Initializing it to 0 fixes the error, and the program prints `5`.

## 3 Choosing int, double, or boolean

An `int` value is an integer, a `double` value is a real number, and a `boolean` value is either `true` or `false`. Pick the type that matches what the data means: counts and positions are `int`; measurements, averages, and rates are `double`; yes/no facts are `boolean`.

The way a literal is written tells Java its type. `42` is an `int`, `42.0` is a `double`, and `true` is a `boolean`. Java will automatically widen an `int` value into a `double` variable, because no information is lost, but it will not automatically store a `double` in an `int` variable, because the fractional part could be lost.

The `boolean` type deserves special attention because beginners often avoid it, storing 0 and 1 in an `int` instead. A `boolean` variable, sometimes called a **flag**, records whether something has happened or is true: `boolean foundError = false;` at the start of a check, set to `true` the moment an error is seen. Because it can hold only two values, a `boolean` makes the program's intent obvious and rules out meaningless values such as 7. Name flags so they read as yes/no questions: `isRaining`, `hasPassed`, `gameOver`.

Choosing between `int` and `double` sometimes depends on precision. Money is a good example: a price such as 4.99 looks like a `double`, but because `double` values can carry tiny rounding errors, programs that must be exact often count money in whole cents with an `int` (499 cents). Neither choice is wrong in general; the right one depends on what the program must guarantee.

**Figure 3.** The way a value is written determines its type. A whole number without a decimal point is an `int`; adding `.0` makes it a `double`; quotes make it a `String`.

Worked Example 3 Literal types

### int Into double, but Not Back

Predict which segment compiles and what it prints.

Segment A

```
double distance = 26;
System.out.println(distance);
```

Output

```
26.0
```

Segment B

```
int laps = 26.2;
```

1. 1 **Segment A.** The `int` literal 26 is automatically widened to the `double` 26.0, so it compiles and prints 26.0.
2. 2 **Segment B.** Storing 26.2 in an `int` would discard .2, so the compiler refuses with a "possible lossy conversion" error.

**Result:** A compiles and prints `26.0`; B does not compile. Java widens `int` to `double` automatically, but never narrows without an explicit cast.

Common Mistake 1 · Writing 5 When You Mean 5.0, or the Reverse

Literal forms change results. `double half = 1 / 2;` stores 0.0, because `1 / 2` is integer division, computed before the value is stored. `int n = 5.0;` does not compile at all. Decide whether each literal should be an integer or a real number and write it accordingly.

## 4 Naming Variables

Variable names, also called **identifiers**, must follow Java's rules: they may contain letters, digits, and underscores; they cannot begin with a digit; they cannot contain spaces or symbols such as hyphens; and they cannot be reserved words such as `int`, `class`, or `public`. Names are case-sensitive, so `total` and `Total` are two different variables.

Beyond the rules, good names follow conventions that make code readable. Java programmers write variable names in **camelCase**: the first word in lowercase and each later word capitalized, as in `totalPoints` or `isGameOver`. Names should describe what the variable holds. `averageScore` explains itself; `a` or `x2` forces every reader to guess. Boolean variables often start with *is* or *has*, so that conditions read like questions: `if (hasKey)`.

**Figure 4.** Names may use letters, digits, and underscores, must not start with a digit, cannot contain spaces or symbols such as hyphens, and cannot be reserved words. Java programmers write variable names in camelCase.

| Rule or convention | Required by Java? | Example |
| --- | --- | --- |
| Use letters, digits, and underscores only | Yes | `max_speed` is legal; `high-score` is not |
| Do not start with a digit | Yes | `player2`, not `2player` |
| Do not use reserved words | Yes | Not `int`, `class`, `double` |
| Names are case-sensitive | Yes | `score` and `Score` are different |
| Use camelCase for variables | Convention | `totalPoints` |
| Use ALL_CAPS for constants | Convention | `MAX_PLAYERS` |
| Choose descriptive names | Convention | `averageScore` rather than `a` |

Worked Example 4 Naming

### Spotting Illegal Names

Each line tries to declare a variable. Which compile?

Line A

```
int 2ndPlace = 2;
```

Line B

```
int class = 30;
```

Line C

```
int secondPlace = 2;
int classSize = 30;
System.out.println(secondPlace + classSize);
```

Output

```
32
```

1. 1 **Line A fails.** A name cannot begin with a digit.
2. 2 **Line B fails.** `class` is a reserved word in Java and cannot be used as a name.
3. 3 **Line C compiles.** `secondPlace` and `classSize` follow the rules and the camelCase convention.

**Result:** Only the names in Line C are legal; the segment prints `32`. Good names are legal, descriptive, and written in camelCase.

Common Mistake 2 · Mixing Up Similar Names

Because Java is case-sensitive, declaring `totalScore` and later typing `totalscore` produces a *cannot find symbol* error. Worse, declaring both `count` and `counts` in the same program invites logic errors when the wrong one is updated. Choose clearly different, descriptive names and spell them consistently.

## 5 Changing a Variable's Value

After a variable is declared, the assignment operator `=` can store a new value in it at any time: `score = 15;`. The type is not repeated, because the variable already exists; writing `int score = 15;` a second time would try to declare a second variable with the same name, which is an error.

Many assignments use the variable's current value to compute its new value, as in `score = score + 10;`. Java evaluates the entire right side first, using the value currently stored, and then stores the result back into the variable. Reading this as "score becomes score plus 10" avoids the mathematical confusion of reading it as an equation.

Worked Example 5 Changing values

### Tracing Reassignments

Trace the value of `steps` after each statement and predict the output.

Code

```
int steps = 1200;
steps = steps + 800;
steps = 500;
steps = steps * 2;
System.out.println(steps);
```

Output

```
1000
```

1. 1 **Line 1.** `steps` is declared and initialized to 1200.
2. 2 **Line 2.** The right side is evaluated first using the current value: 1200 + 800 = 2000, which is stored back.
3. 3 **Line 3.** 500 replaces 2000. Earlier values are gone.
4. 4 **Line 4.** 500 × 2 = 1000.

**Result:** `steps` goes 1200 → 2000 → 500 → 1000, and the program prints `1000`. Only the most recent assignment matters.

| Statement | steps after the statement |
| --- | --- |
| int steps = 1200; | 1200 |
| steps = steps + 800; | 2000 |
| steps = 500; | 500 |
| steps = steps * 2; | 1000 |

Common Mistake 3 · Redeclaring an Existing Variable

Once `int lives = 3;` has been written, later changes must be written `lives = 2;`, without the type. Repeating `int` tells the compiler to create a brand-new variable, and declaring the same name twice in the same part of a program is a compile-time error.

## 6 Constants With final

Some values should never change while a program runs: the number of days in a week, a tax rate, the maximum number of players. Declaring a variable with the keyword `final` makes it a **constant**: it can be assigned once, and any later attempt to change it is a compile-time error. By convention, constants are named in all capital letters with underscores between words, such as `MAX_PLAYERS`.

Named constants make programs easier to read and to change. `total * TAX_RATE` explains itself, while `total * 0.08` leaves the reader wondering what 0.08 means. If the rate changes, updating one constant updates every calculation that uses it.

Worked Example 6 Constants

### Values That Should Never Change

A program uses the number of minutes in an hour. Declare it as a constant and show what happens if code tries to change it.

Using a constant

```
final int MINUTES_PER_HOUR = 60;
int total = 3 * MINUTES_PER_HOUR;
System.out.println(total);
```

Output

```
180
```

Trying to change it

```
final int MINUTES_PER_HOUR = 60;
MINUTES_PER_HOUR = 90;
```

1. 1 **The keyword `final`.** A `final` variable can be assigned only once. Afterward, any attempt to change it is a compile-time error.
2. 2 **Naming convention.** Constants are written in all capital letters with underscores between words, which signals to readers that the value is fixed.
3. 3 **Why bother.** A named constant explains what a number means and prevents accidental changes.

**Result:** The first segment prints `180`; the second does not compile because a `final` variable cannot be reassigned.

Common Mistake 4 · Using Unexplained Numbers Throughout the Code

Numbers such as 60, 0.08, or 12 scattered through a program are sometimes called "magic numbers": their meaning is invisible, and if one changes, every copy must be found and updated. Replace them with well-named constants declared once near the top of the code.

### Four Habits for Declaring Variables

#### 1. Declare and Initialize Together

Give every variable a sensible starting value when you create it.

#### 2. Match the Type to the Meaning

Counts int, measurements double, yes/no boolean.

#### 3. Name for the Reader

Descriptive camelCase names; is/has for booleans; ALL_CAPS for constants.

#### 4. Declare Once, Assign Often

Write the type only in the declaration; later changes use just the name.

Core Synthesis

The three primitive data types used here are `int`, `double`, and `boolean`: an `int` value is an integer, a `double` value is a real number, and a `boolean` value is true or false. A variable is a storage location that holds a value, which can change while the program runs; every variable has a name and an associated data type, and a variable of a primitive type holds a primitive value from that type. Variables are declared with a type and a name, must be initialized before use, follow Java's naming rules and conventions, and can be made constant with `final`.

FiveStudy AP® Computer Science A Study Guide · Using Objects and Methods · Primitive Variable Declarations Back to top ↑
