Changing a value
A variable's value can change while the program runs. To give an existing variable a new value, write its name, = and the value, without the type in front:
int lives = 3;
System.out.println("Lives: " + lives);
lives = 2;
System.out.println("Lives: " + lives);
Lives: 3
Lives: 2The = here means "put this value into the variable", not "is equal to". The old value is gone after the assignment.
Create once, change many times
The type is written only once, when the variable is created. Writing it again creates a second variable with the same name, which Java doesn't allow:
public class Main {
public static void main(String[] args) {
int points = 10;
int points = 25;
System.out.println(points);
}
}
Main.java:4: error: variable points is already defined in method main(String[])
int points = 25;
^
1 errorAnd the type stays the same for the variable's whole life: an int variable can't later hold text. age = "twenty"; fails with incompatible types: String cannot be converted to int.