Java Variables
A variable is a named storage place for a value in a Java program. Each variable has a type that states the kind of value it can hold.
Typed declarations
The score variable holds a whole number. The player variable holds text.
public class Main {
public static void main(String[] args) {
int score = 10;
String player = "Ada";
System.out.println(score);
System.out.println(player);
}
}A value given later
The count variable starts with no value on its line. The next line gives it the value 5.
public class Main {
public static void main(String[] args) {
int count;
count = 5;
System.out.println(count);
}
}A value can change
The level variable first holds 1 and then holds 2. The print line shows the last value.
public class Main {
public static void main(String[] args) {
int level = 1;
level = 2;
System.out.println(level);
}
}final refuses a second value
The maxScore variable is marked final. The compiler refuses the second value.
public class Main {
public static void main(String[] args) {
final int maxScore = 100;
maxScore = 200;
System.out.println(maxScore);
}
}Example
public class Main {
public static void main(String[] args) {
String city = "Oslo";
int visits = 2;
visits = 3;
System.out.println(city);
System.out.println(visits);
}
}Key points
- A declaration writes a type, then a name, then a value.
- A variable can be declared first and given a value later.
- A stored value can change to a new value of the same type.
- A printed variable prints its current value.
- The final keyword marks a variable that keeps its first value.
- A final variable refuses a second value.
In this example, city holds the text Oslo and visits holds 2. The visits variable then takes the new value 3. The print lines show Oslo and the current value 3.
Note
A variable name starts with a letter in the programs in this course.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What does the final keyword do to a variable?