Video lecture
Watch on YouTube(opens in a new tab)Sub topic 3
Declaring, Initializing, and Updating Variables
A variable is a named place where a program keeps a value. For example, a game might use a variable named score to keep track of a player’s points. As the player earns points, the program can change that value.
In Java, every variable has a type. A type tells Java what kind of value the variable can hold. For example, int is a type for whole numbers, and boolean is a type for true or false.
This chapter shows how to create a variable, give it a starting value, and change it.
Declaring a variable
A declaration introduces a variable and states its type. This declaration creates a variable named count that can hold an int value:
int count;
The type comes first, followed by the name. The semicolon marks the end of the statement. A statement is an instruction in a Java program.
After this declaration, Java knows the name and type of count. But this local variable does not yet have a value that your code can read. A local variable is a variable declared inside a method or a smaller block of code.
Initializing a variable
Initialization gives a variable its first value. You can initialize count after declaring it:
count = 3;
The equals sign here is the assignment operator. An operator is a symbol that tells Java to perform an action. Assignment puts the value on the right into the variable on the left.
You can also declare and initialize a variable in one statement:
int count = 3;
Here, 3 is a literal: a value written directly in the code. The type is still int, and the variable name is still count.
You must give a local variable a value before you read it. For example, after int count;, trying to print count before assigning it a value causes a compile error. A compile error is a problem Java reports when it checks and translates your code before running it.
Updating a variable
After initialization, you can use assignment to replace the value:
count = 5;
Do not repeat the type when updating the variable. If count is already declared in the same block, writing int count = 5; again tries to declare a second variable with the same name and causes an error.
An update can use the variable’s current value:
count = count + 1;
The code on the right of = is an expression. An expression is code that produces a value. Java reads the current value of count, adds 1, and assigns the result back to count.
For example, if count is 3 before this statement, it is 4 afterward. The statement does not mean that count will always be one greater than itself. It describes an action that happens when Java runs it.
Walk through a complete program
Save the following program in a file named VariableExample.java:
class VariableExample {
public static void main(String[] args) {
int count;
count = 3;
System.out.println("Starting count: " + count);
count = count + 1;
System.out.println("After adding one: " + count);
int savedCount = count;
count += 2;
count++;
System.out.println("Current count: " + count);
System.out.println("Saved count: " + savedCount);
boolean ready = false;
ready = true;
System.out.println("Ready: " + ready);
}
}With the Java Development Kit installed, run these commands in the folder containing the file:
javac VariableExample.java
java VariableExampleThe output is:
Starting count: 3
After adding one: 4
Current count: 7
Saved count: 4
Ready: trueSystem.out.println prints a line. In these print statements, + joins a text label to a value.
Follow the count
The program declares count and then initializes it to 3. It prints that starting value. Next, count = count + 1; changes it to 4.
The program then declares savedCount and initializes it with the current value of count, which is 4. Later changes to count do not change savedCount. The two variables hold separate values.
The next two statements are shorter ways to update count:
count += 2;adds2to the current value ofcount. It changes4to6.count++;adds1to the current value ofcount. It changes6to7.
The example uses count++ as a statement by itself. For now, that is a clear way to use it: the statement’s job is simply to increase the count.
Finally, the program declares ready with the value false, then assigns true to it. This shows that updating is not limited to numbers.
Choose clear names
A variable name should help a reader understand what the value represents. For example, itemCount is more helpful than x when the value counts items.
Java names are case-sensitive. That means count, Count, and COUNT are different names. If you declare count, you must use the same spelling and capitalization when you read or update it.
A common Java style is to start a variable name with a lowercase letter and capitalize later words, as in savedCount. This style is called camel case.
Keep these rules in mind:
- A name cannot contain spaces. Use
itemCount, notitem count. - A name cannot begin with a digit. Use
level2, not2level. - A hyphen is not a joiner in a name; Java reads
-as an operator. UsehighScore, nothigh-score. - A Java keyword cannot be a variable name. A keyword is a word Java reserves for a special purpose, such as
intorclass.
Match the value to the type
The type in a declaration stays attached to that variable. An int variable can hold a whole-number value, while a boolean variable can hold true or false.
| Statement | Result |
|---|---|
| `int lives = 3;` | Declares and initializes a whole-number variable. |
| `lives = 2;` | Updates the existing variable. |
| `boolean active = true;` | Declares and initializes a true-or-false variable. |
| `lives = true;` | Causes an error because `true` is not an `int` value. |
Likewise, int lives = 2.5; causes an error: 2.5 is not an int value. Choose a suitable type when declaring a variable, and assign values that Java allows for that type.
Check common mistakes
If a declaration or update does not work as expected, check these points:
- Missing semicolon: End a declaration or assignment statement with
;. - Reading too early: Give a local variable a value before printing it or using it in an expression.
- Wrong capitalization:
savedCountandsavedcountare different names. - Declaring again: To change an existing variable, write
count = 5;, not anotherint count = 5;in the same block. - Wrong type of value: Check that the value on the right can be assigned to the variable’s type.
- Reversing assignment: In
count = 3;, the variable being changed is on the left. Writing3 = count;is not valid.
Practice
For each exercise, try the question before reading the answer. Assume each statement runs in order inside a method.
Exercise
After int points;, points = 2;, and points = points + 3;, what is the value of points?
Show answer
It is 5. The first assignment initializes points to 2, and the update adds 3.
Exercise
A block already contains int count = 3;. How do you change count to 8 without declaring it again?
Show answer
Write count = 8;.
Exercise
After int first = 4;, int second = first;, and first = 9;, what are the two values?
Show answer
first is 9 and second is 4. Changing first does not change the value already stored in second.