A variable is a name given to a particular area in memory that stores a value, which can later be reused. When creating a variable in Java it is necessary to specify the type of data to be stored within the variable, for example, whether it is a string, integer or floating-point number. The value of a variable can be changed as much as is necessary once it has been created.
When naming variables in Java it should be noted that the names are case sensitive, as are the datatypes. The names must start with a letter, dollar sign, or underscore, followed by letters, numbers, dollar signs or underscores. Although permitted, by convention, dollar signs and underscores are rarely used to start a variable name, indeed, dollar signs are often not used at all anywhere in a name. There is no limit to the length of a variable name, although in practice, really long names introduce unnecessary complexity.
Another convention, when naming variables is to use camel case, so if a name is made up of more than one word, use a lower-case letter at the start of the first word and then upper case letters at the start of words thereafter, for example, ‘firstName’ and ‘dateOfBirth’.
When declaring a variable, it takes the following format.
type name = initial_value;
The ‘type’ refers to the datatype of the value that can be held in the variable, such as an integer, ‘name’ is the name of the variable, so that it can be referenced later, and finally, ‘initial_value’ is the value given to the variable when it is declared. A variable doesn’t need to be initialised when it is declared, it can be done later, so a variable declaration can be shortened to that shown below.
Unlike some programming languages, such as PL/SQL, variables in Java can be declared at the point at which they are need, instead of at the top of a programme, or block, in the case of PL/SQL.
Below are some examples of variable declarations. It should be noted that, in order for date and time variables to work, ‘java.time.LocalDateTime’ needs to be imported.
String firstName = "Fred"; // A string variable. int age = 30; // An integer variable. float price = 12.99; // A float variable. boolean result = true; // A boolean variable. LocalDateTime current = LocalDateTime.now(); // A datetime variable with the current date and time.
Multiple variables of the same type can also be declared together in a single line of code.
int x, y, z;
Here three integer variables, x, y and z, have been declared together. Multiple variables can also be declared and initialised in one line of code.
int x = 10, y = 20, z = 30;
One final thing to note is that variable names must not be the same as reserved words in the Java programming language. Reserved words, including all those shown in blue above, have a specific meaning and cannot be used for anything else.