Sub topic 1
Variables and Types
A value is a piece of data, such as the number 3. A variable is a named place that holds a value. You can use the name to read the value or give the variable a new one.
A type describes what kind of value a variable can hold and what you can do with it. For example, Java uses the type int for whole numbers and double for numbers that can have a fractional part.
Types help Java catch mistakes. If a variable has type int, you cannot put a word such as “three” into it. The variable’s type stays the same, even when its value changes.
A worked example
This program tracks the number of tickets and the price of one ticket.
class VariablesExample {
public static void main(String[] args) {
int tickets = 3;
double ticketPrice = 12.5;
System.out.println("Tickets: " + tickets);
System.out.println("Price: " + ticketPrice);
tickets = tickets + 1;
System.out.println("Tickets now: " + tickets);
}
}A class is a named container for code. Here, the class is named VariablesExample. A method is a named group of instructions. Java starts this program in the method named main.
Save the code in a file named VariablesExample.java. With the Java tools installed, open a terminal, a window where you can enter commands, in the same folder. Run:
javac VariablesExample.java
java VariablesExampleThe first command uses a compiler, a tool that checks and translates Java code. The second runs the program. It prints these lines:
| Printed line | What it shows |
|---|---|
| Tickets: 3 | The first value of tickets |
| Price: 12.5 | The value of ticketPrice |
| Tickets now: 4 | The value of tickets after it changes |
Follow the values
The line that starts with int creates a variable named tickets and gives it the value 3. The next line creates a double variable named ticketPrice and gives it the value 12.5.
Each System.out.println line tells Java to print a line. The text inside the quotation marks is a label. The plus sign joins that label to the value of the variable, so the reader can tell what the number means.
Later, the program gives tickets a new value:
- Java reads the current value of tickets, which is 3.
- It adds 1 to get 4.
- It stores 4 in tickets, replacing the old value.
The equals sign in these lines tells Java to store the value on the right in the variable on the left. It does not ask whether the two sides are equal.
Check your understanding
Exercise
If tickets starts at 3 and the program adds 2 to it, what value does tickets hold afterward? Does its type change?
Show answer
It holds 5. Its type remains int.
Exercise
Why is double a better fit than int for the ticket price 12.5?
Show answer
The price has a fractional part. An int holds whole numbers, while a double can hold a value such as 12.5.