Variables
What you'll learn:
- declare a variable with a type, put a new value into it and read it;
- name Java's eight primitive types and write numbers such as
10Land2.5f; - declare variables with
varand forbid changing them withfinal; - explain why a field with no value can be read while a local variable cannot.
Picture a box with a label. The label carries a name, and the box holds a value. By the name you can find the box, look inside or put something else in it. A program keeps its data the same way, in variables: named values that can be read and changed.
A box also has a shape. A box for whole numbers takes no text, and a box for text takes no number. Java calls the shape of the box its type, and you state it right when you create the variable.
Before you put anything into a box, you have to set it up and label it. Java requires a variable to be declared before its first use. Let's see what happens if it is not:
public class Main {
public static void main(String[] args) {
age = 30; // ✗
System.out.println(age);
}
}error: cannot find symbolThe compiler does not know the name age: nobody declared a variable with that name. It does not create one on its own, even when it sees something being put into it.
Declaring a variable
A declaration tells the compiler the type and the name of a new variable. Usually it gives the first value as well:
int age = 30;
System.out.println(age); // 30
System.out.println("age"); // ageThe line int age = 30; reads from left to right:
intis the type: a whole number;ageis the variable's name;= 30is the initial value;;ends the statement, as after every command in Java.
Let's walk through what the next two lines print:
System.out.println(age)prints the variable's value,30.System.out.println("age")prints the text in quotes, the wordage.
The only difference is the quotes. Without them Java looks for a variable with that name, and with them it prints the text itself.
Declare first, assign later
You can also declare a variable with no value and put the value in later:
int score;sets up a box for a whole number, with no value yet;score = 10;puts10into it.
Until something is put into score, it cannot be read. The compiler keeps track of this and rejects a program that reads a variable before it has been given a value.
Assignment and a copy of the value
The = operator puts a new value into a variable that is already declared, and the old value is gone. This operation is called assignment. Now let's see what happens when another variable stands to the right of =:
int a = 3;
int b = a;
a = 5;
System.out.println(a); // 5
System.out.println(b); // 3Let's go line by line:
int a = 3;sets up boxaand puts3into it.int b = a;sets up boxband puts into it a copy of what is ina, the number3.a = 5;changes onlya.System.out.println(a)prints5.System.out.println(b)prints3:bholds its own three and does not followa.
The line int b = a does not tie two variables together for good. It copies the value once, and from then on each box lives on its own. The widget runs the same program plus two more lines: press "Next step" and watch what is in a and b.
1public class Main {2 public static void main(String[] args) {3 int a = 3;4 int b = a;5 a = 5;6 System.out.println(a);7 System.out.println(b);8 b = 7;9 System.out.println(a);10 }11}
The program starts in main, and there are no variables yet.
This is where the box picture falls short. A real thing can only be moved out of a box, and then the box is empty. But int b = a puts a copy into b, and everything stays in a. Reading takes nothing away either: after System.out.println(a), a holds the same number.
Variable names
Pick a name that tells what is inside: age, price, itemCount. The rules are:
- a name starts with a letter and is made of letters, digits and the underscore
_; - a compound name is written as one word, each next word starting with a capital letter:
itemCount,maxSpeed; - case matters:
ageandAgeare two different variables; - Java keywords such as
intorclasscannot be names.
Common mistake
A variable was declared with no value and read right away:
int score;
System.out.println(score); // ✗error: variable score might not have been initializedThe program does not compile. A variable declared inside main gets no value by itself, and the compiler checks that something has been put into it before every read. Give it a value before the read, for example int score = 0;, and the program prints 0.
Key points
- A variable is declared before its first use: type, name and usually an initial value, as in
int age = 30;. =puts a new value into a variable, and the old one is gone.int b = acopies the value once, so a latera = 5does not changeb.- A variable inside
maincannot be read until it has been given a value; otherwise the program does not compile.