Sub topic 3
Declaring, Initializing, and Updating Variables
A variable is a named place to store a value. A value is a piece of data, such as a number. Variables let a program remember information and change it as the program runs.
Every Java variable has a type. A type says what kind of value the variable can hold. For example, int is a type for whole numbers.
Declare and initialize
A declaration introduces a variable by giving its type and name. For example, int count; declares a variable named count.
Initialization gives a variable its first value. You can declare and initialize a variable in one step: int count = 3;. The equals sign assigns the value 3 to count.
You can also declare a variable first and give it a value later. In either case, give a local variable a value before you try to read it. A local variable is a variable declared inside a method, such as main.
Work through an example
Save this program in a file named VariableExample.java:
class VariableExample {
public static void main(String[] args) {
int count = 3;
int bonus;
bonus = 2;
System.out.println(count);
count = count + bonus;
System.out.println(count);
count = count + 1;
System.out.println(count);
}
}With the Java Development Kit (JDK) installed, run these commands in the folder containing the file. The JDK provides the tools used to build and run Java programs.
javac VariableExample.java
java VariableExampleThe program prints 3, 5, and 6, each on a new line.
Here is what happens:
int count = 3;declares and initializescount.int bonus;declaresbonus. The next line initializes it with2.- The first print instruction shows the current value of
count, which is3. count = count + bonus;adds3and2, then stores the result,5, incount.count = count + 1;adds1to the current value ofcountand stores6incount.
An assignment stores a value in a variable. The code on the right of = is worked out first. Then its result is stored in the variable on the left. So count = count + 1; uses the old value of count to find its new value.
Avoid common mistakes
Each variable instruction in the example ends with a semicolon (;). Leaving one out causes an error.
Use the type when you declare a variable, but do not repeat it when you update that variable. For example, write count = 4; to update count, not int count = 4;. Declaring another local variable named count in the same block causes an error.
Names also matter: Java treats count and Count as different names. Finally, assign a value that fits the declared type. For example, an int variable cannot hold the word hello.
Exercise
If count starts at 3, what value does it hold after count = count + 2; and then count = count + 1;?
Show answer
It holds 6. The first assignment changes it to 5, and the second changes it to 6.