Loading lessons...
Java Variables
Java Variables
A variable is a container that stores a value. In Java you must always declare the type of a variable before you use it.
Declaring a variable
Use the type, a name, an equals sign, and a value:
int myNum = 5;
String name = "John";
Here int stores whole numbers and String stores text.
Changing the value
You can change a variable later by assigning a new value:
int myNum = 5;
myNum = 10;
System.out.println(myNum);
This prints 10.
Final variables
The final keyword makes a variable constant, so its value cannot be changed:
final int myNum = 15;
// myNum = 20; this will cause an error
Naming rules
- Names are case sensitive.
- They must start with a letter, underscore
_, or dollar sign$. - Use camelCase, like
myNumber, for multiple words. - Avoid reserved keywords like
intorclass.
Combining declaration and use
int a = 5;
int b = 3;
int sum = a + b;
System.out.println(sum);
TL;DR
- Declare variables with a type, name, and value.
- Values can be changed unless the variable is
final. - Follow naming rules and use camelCase.