Variable declaration syntax (single line):
Type identifier = value;
or (assignment statement in 2nd line):
Type identifier;
identifier = value;
Naming variables
There are rules and conventions around how Java variables are named.
A Java variable name:
- should begin with a lowercase letter
- can contain numbers
- can contain an underscore
- must be less than 255 characters long
- must not contain spaces
- must not begin with a number
- if the name consists of more than word, capitalize the first letter of each word
Case sensitive
All names in Java are case sensitive. This means that a variable named numberOfClicks is different to a variable named numberofclicks.
Variable Declaration
When we create a variable in our program, we are said to be ‘Declaring a variable’. Variables are declared in methods. Methods are named blocks of code which perform a particular task. Variables may also be declared in the body of a class - that is, within the class declaration, but not within the body of a method.
When we declare a variable, we are telling the program to remember a value. Of course, there are many different types of data so we need to select the most appropriate variable type to store that value in.
The statement below is a variable declaration for some String data called myPassword. The value it is storing is “secret’.
String myPassword = “secret”;
Assigning values - The assignment operator
When we assign a value to a variable, we use the assignment operator - the equals (=) character.
The assignment operator takes the value on the right and assigns it to the operand on the left side to form an assignment expression.
In the example below, the value “GateKeeper99” has been assigned to the String variable called myUserName.
String myUsername = “GateKeeper99”;
The assignment operator is also used to change the value being stored by the variable, as follows:
int numberOfUsers = 100;
numberOfUsers = 101;
We are also able to declare a variable in one statement and assign a value to it, in another statement.
As follows:
int xCoordinate;
xCoordinate = 500;
This technique is often used where we need to increase the scope of a variable.
Variable scope
A variable may only be referenced from within the region where it is declared. This means that if a variable is declared within a method, it is only accessible from within that method. Also, you cannot reference a variable before it is declared. If a variable is declared in the class body, this variable can be accessed from all methods in the class.
Variable lifetime
Variable lifetime refers to the length of time that a variable stores a value. Depending on the scope, a variable may have a lifetime that lasts for the time it takes a single block of code to execute, or for the entirety of program execution (more on that later).

