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.
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.
1What 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.
2Declaring 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.
= 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; |
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.
int lives = 3;
double health = 100.0;
boolean hasKey = false;
int coins = 0;
System.out.println(lives + " " + health + " " + hasKey + " " + coins);
3 100.0 false 0
- 1Choose types by meaning. Lives and coins are counts (
int), health can be fractional (double), and holding a key is yes/no (boolean). - 2Choose descriptive names.
hasKeyreads naturally in a condition later: "if the character has the key." - 3Initialize when declaring. Giving each variable its starting value in the declaration avoids using a variable before it has a value.
3 100.0 false 0. Notice that the double prints with a decimal point even when its value is a whole number.Using a Variable Before It Has a Value
Explain why this code does not compile, and fix it.
int total;
total = total + 5;
System.out.println(total);
- 1The problem.
totalis 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. - 2The fix. Initialize it first.
Fixed
int total = 0; total = total + 5; System.out.println(total);Output5
total might not have been initialized. Initializing it to 0 fixes the error, and the program prints 5.3Choosing 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.
int; adding .0 makes it a double; quotes make it a String.int Into double, but Not Back
Predict which segment compiles and what it prints.
double distance = 26;
System.out.println(distance);
26.0
int laps = 26.2;
- 1Segment A. The
intliteral 26 is automatically widened to thedouble26.0, so it compiles and prints 26.0. - 2Segment B. Storing 26.2 in an
intwould discard .2, so the compiler refuses with a "possible lossy conversion" error.
26.0; B does not compile. Java widens int to double automatically, but never narrows without an explicit cast.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.
4Naming 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).
| 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 |
Spotting Illegal Names
Each line tries to declare a variable. Which compile?
int 2ndPlace = 2;
int class = 30;
int secondPlace = 2;
int classSize = 30;
System.out.println(secondPlace + classSize);
32
- 1Line A fails. A name cannot begin with a digit.
- 2Line B fails.
classis a reserved word in Java and cannot be used as a name. - 3Line C compiles.
secondPlaceandclassSizefollow the rules and the camelCase convention.
32. Good names are legal, descriptive, and written in camelCase.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.
5Changing 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.
Tracing Reassignments
Trace the value of steps after each statement and predict the output.
int steps = 1200;
steps = steps + 800;
steps = 500;
steps = steps * 2;
System.out.println(steps);
1000
- 1Line 1.
stepsis declared and initialized to 1200. - 2Line 2. The right side is evaluated first using the current value: 1200 + 800 = 2000, which is stored back.
- 3Line 3. 500 replaces 2000. Earlier values are gone.
- 4Line 4. 500 × 2 = 1000.
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 |
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.
6Constants 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.
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.
final int MINUTES_PER_HOUR = 60;
int total = 3 * MINUTES_PER_HOUR;
System.out.println(total);
180
final int MINUTES_PER_HOUR = 60;
MINUTES_PER_HOUR = 90;
- 1The keyword
final. Afinalvariable can be assigned only once. Afterward, any attempt to change it is a compile-time error. - 2Naming convention. Constants are written in all capital letters with underscores between words, which signals to readers that the value is fixed.
- 3Why bother. A named constant explains what a number means and prevents accidental changes.
180; the second does not compile because a final variable cannot be reassigned.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.
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.