A variable is a location in the computer’s memory where a value is stored and from which the value can be retrieved later.
Variables are used in a java program to store data that changes during the execution of the program. They are the basic units of storage in a java program. Variables can be declared to store values such as names, addresses and salary details.
Variables must be declared before they can be used:
datatype is a valid data type in java.
Variablename is a valid variable name.
The above statements declare an integer variable called rollNumber, and a character variable called gender. These statements instruct the operating system to allocate the required amount of memory to each variable in order to hold the type of data specified for each. Additionally, each statement also provides a name that can be used within the program to access the values stored in each of the variables.
Rules and Conventions
Java programming language has its own set of rules and conventions that need to be followed for naming variables. For a start, variable names should be short and meaningful.
Not adhering to the rules will result in syntax errors. Naming conventions are to be followed as they ensure good programming practices.
The rules and conventions for naming variables are:
Variable names may consist of Unicode letters and digits, underscore(_), and dollar sign ($).
A variable’s name must begin with a letter, the dollar sign ($), or the underscore character (_). The convention, however, is to always begin your variable names with a letter, not “$” or “_”.
Variable names must not be a keyword or reserved word in java.
Variable names in java are case-sensitive (for example, the variable names number and number refer to two different variables).
If a variable name comprises a single word, the name should be in lowercase(for example, velocity or ratio).
If the variable name consists of more than one word, the first letter of each subsequent word should be capitalized (for example, employeeNumber and accountBalance).
Note: Unicode is a 16-bit character set, which contains all the characters commonly used in information processing. It is an attempt to consolidate the alphabets of the world’s various languages into a single and international character set.
The table shown below contains some example of valid and invalid java variable names:
Valid / Invalid
Invalid and contains the illegal character #
Invalid and is a keyword
Invalid and first character is a digit