Java Variables
A variable is a named box in memory where your program keeps a value it wants to remember and reuse. In Java, every variable has a type that is fixed the moment you declare it, so the compiler always knows what kind of data lives inside.
Declaring a variable
To create a variable in Java you write its type, then its name, and usually an initial value. The type tells Java how much space to reserve and what operations are allowed; the name is how you refer to that value later in your code. This pairing of a type with a name is what makes Java a statically typed language.
Declaring and using a variable
public class Main {
public static void main(String[] args) {
int score = 42;
System.out.println(score);
}
}You can declare a variable on one line and assign it a value later. The variable is not usable until it actually holds a value, so Java will refuse to compile code that reads a local variable before it has been set.
Declare first, assign later
public class Main {
public static void main(String[] args) {
String greeting;
greeting = "Hello, Java";
System.out.println(greeting);
}
}Common variable types
Beginners meet a handful of types again and again. Here are the ones you will use most often when you are starting out.
Naming rules and conventions
- A name may contain letters, digits, the underscore, and the dollar sign, but it cannot start with a digit.
- Names are case sensitive, so count and Count are two different variables.
- You cannot use reserved words such as int, class, or public as a name.
- By convention, variable names use lowerCamelCase, for example totalPrice or userName.
- Choose descriptive names; daysLeft reads far better than the mysterious d.
Changing a value
A normal variable can be reassigned as many times as you like, as long as the new value has the same type. Reassigning simply replaces the old contents of the box with the new value.
Reassigning a variable
public class Main {
public static void main(String[] args) {
int lives = 3;
lives = lives - 1;
System.out.println("Lives left: " + lives);
}
}Exercise: Java Variables
Which keyword prevents a variable's value from being changed after it is set?