Variables
A variable is a named memory location that can be changed during the program’s execution. It has three properties:
- A type.
- A value.
- A name or identifier.
Identifiers
Not all identifiers are valid. They can be an sequence of alphanumeric characters, $
and _
unless:
- They start with a number.
- It is a keyword.
Identifiers are case sensitive.
Conventions
- Class names start in capital letters.
- Method and variable names start in lower case letters.
- CamelCase is used if several words make up and identifier.
Example
In the following code all of the following keywords are identifiers:
HelloWorld
, main
, String
, args
, System
, out
and println
.
public class HelloWorld {
// Main Method
public static void main(String[] args) {
System.out.println(*"Hello World");
}
}
Variable Declarations
A declaration statement declares a variable to be of a particular type and is of the form:
<type> <variableName>;
where <type>
is a type and <variableName>
a legal identifier.
double currentWeight;
int studentsLearningJava;
int maximumValue;
Variables must be declared before you can use them.
Variable Assignments
An assignment statement stores a value in a variable as follows:
<variableName> = <value>;
<variableName>
may be any already declared identifier.<value>
is a value of the same type as<variableName>
.
Declaration and Initialisation
We can also combine declaration a variable with the assignment of an initial value (initialisation) as follows:
<type> <variableName> = <value>;
double currentWeight = 122.5;
int studentsLearningJava = 78;