Video lecture
Watch on YouTube(opens in a new tab)Sub topic 1
Variables and Types
What is a variable?
A program often needs to remember information while it runs. A game might need to remember a player’s score. A shopping program might need to remember how many items are in a cart.
A variable is a named place in a program that holds a value. A value is a piece of information, such as the number 3 or the answer true.
You can think of a variable as a labeled box. The label is its name, and the contents are its current value. As the program runs, it can read the value or replace it with another one.
For example, a variable named score could hold 3 at the start of a game. After the player earns a point, it could hold 4.
The name score is not the value itself. It is how the program refers to the variable. The value is the information currently held there.
What does a type do?
A type tells Java what kind of value a variable can hold and helps determine which operations are allowed with it.
For example:
intis a type for whole numbers, such as3and4.booleanis a type for the two valuestrueandfalse.
A variable’s declared type is the type given when the variable is created in the code. If score is declared as an int, it can hold an appropriate whole-number value. It cannot hold true.
A variable’s value can change, but its declared type does not change. If an int variable holds 3 and later holds 4, it is still an int variable.
Types help catch mistakes. A compiler is a tool that checks Java code and translates it into a form Java can run. For example, the compiler rejects an attempt to put true into an int variable.
A type check cannot catch every mistake. If a game adds two points when it should add one, the values may still be valid int values. The program can be valid Java and still give the wrong result.
A worked example
The following program creates variables, reads their values, and changes one of them.
class VariablesAndTypes {
public static void main(String[] args) {
int score = 3;
int savedScore = score;
boolean ready = true;
System.out.println(score);
System.out.println(savedScore);
System.out.println(ready);
score = score + 1;
System.out.println(score);
System.out.println(savedScore);
}
}Run the program
Save the code in a file named VariablesAndTypes.java. You need a Java Development Kit installed; it provides the tools used in the following commands.
Open a terminal in the folder that contains the file. A terminal is an application where you enter commands. Run:
javac VariablesAndTypes.java
java VariablesAndTypesThe first command compiles the program. The second runs it. The output is:
3
3
true
4
3Each call to System.out.println prints a value on its own line. When the code gives it a variable name, it prints that variable’s current value.
Follow the values
Look at the first line inside main:
int score = 3;
This line gives the variable the name score and the type int. It also gives the variable its first value, 3.
The next line creates another int variable:
int savedScore = score;
Here, Java reads the current value of score, which is 3, and puts that value in savedScore. Both variables now hold 3, but they are separate variables.
The third line creates a boolean variable named ready and gives it the value true.
Later, the program changes score:
score = score + 1;
Java reads the current value of score, adds 1, and puts the result back into score. The value changes from 3 to 4. The value of savedScore stays 3.
This table tracks the values. A dash means the program has not yet reached the line that creates that variable.
| After this line | `score` | `savedScore` | `ready` |
|---|---|---|---|
| `int score = 3;` | `3` | — | — |
| `int savedScore = score;` | `3` | `3` | — |
| `boolean ready = true;` | `3` | `3` | `true` |
| `score = score + 1;` | `4` | `3` | `true` |
The last two printed values are therefore 4 and 3. Changing score did not also change savedScore.
Reading and changing a value
A program can use a variable’s value without changing it. In the example, System.out.println(score); reads and prints the value. It does not add anything to score.
The equals sign in score = score + 1 does a different job from an equals sign in a math equation. Here, it tells Java to calculate the value on the right and put that value into the variable on the left.
The order matters:
- Read the current value of
score. - Add
1to that value. - Store the result in
score.
Give variables useful names
A good name helps a reader understand what a value means. Compare score with x. Both can be variable names, but score gives a clearer clue about its purpose.
Names such as itemCount, remainingMinutes, and ready also tell a reader something about the information being stored. Clear names make it easier to follow a program and spot mistakes.
Java treats uppercase and lowercase letters as different. The names score and Score do not mean the same thing. If you created score but later try to use Score, Java will not treat that as a use of score.
Variable names cannot contain spaces or start with a digit. For example, itemCount works as a name, while item count does not.
Common mistakes
Mixing up a name and a value
In int score = 3;, score is the name and 3 is the value. The value can later change, while the name remains the way to refer to that variable.
When you see System.out.println(score);, read it as “print the current value of score.” It does not print the word score.
Putting the wrong kind of value in a variable
Suppose a program creates an int variable named score. A later line such as score = true; is not valid. The value true is a boolean value, not an int value. The compiler reports an error for that line.
When a type error occurs, check both sides: what type was the variable declared with, and what kind of value is the code trying to put into it?
Expecting a copied value to keep changing
In the worked example, savedScore receives the value held by score at that moment. It does not track later changes to score. After score becomes 4, savedScore still holds 3.
This distinction matters whenever you want to keep an earlier number for comparison. In the example, the program can print both the new score and the saved score.
Practice
Exercise
A program runs int steps = 5;, then int savedSteps = steps;, then steps = steps + 2;. What value does each variable hold at the end?
Show answer
steps holds 7. savedSteps still holds 5.
Exercise
A variable is created with int points = 2;. Why does points = false; cause a type error?
Show answer
points has the declared type int, but false is a boolean value.
Exercise
In boolean ready = true;, which part is the type, which is the name, and which is the first value?
Show answer
boolean is the type, ready is the name, and true is the first value.