Variable is the named location of memory. Variable is used to store data, that’s why this is called the unit of storage. A value of a variable can be modified during the course of program execution. In Java, you must explicitly declare all variables before using them.
Variable declaration includes:
- Data type
- Variable name
- Initial value (optional)
- A ; (semi colon) at the end of declaration statement.
Syntax for declaring variables:
DateType variableName = value;
Example:
String name = “Shamsuddin”;
Here “String” is the data type, “name” is the variable name and “Shamsuddin” is the initial value.
double radius = 15.69;
Here “double” is the data type, “radius” is the variable name and “15.69” is the initial value.
Rules for naming a variable (identifier):
- Only a limited number of characters can be used for naming a variable. The characters are upper or lowercase letters (a-z or A-Z), numerals (0-9), underscore (_), and dollar sign ($)
- Variables name cannot start with digit (0-9)
- A variable name cannot be same as a Java keyword.
Conventions for naming a variable:
- Variable name should be meaningful
- Should be in mixed case with the first letter lowercase, and then with the first letter of each internal word capitalized
- Variable names should not start with underscore (_) or dollar sign ($) characters, even though both are allowed.
- One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.
Examples:
Invalid Variable Name | Reason | Valid Variable Name |
average income | Contains whitespace | averageIncome |
1stNumber | Starts with digit | firstNumber or number1 |
for | for is a java keyword | formula |
sl.number | Contains dot (.) | slNumber |
Common Errors while using variables:
; (semi-colon) expected
cannot find symbol / cannot resolve symbol
identifier expected
incompatible types
possible loss of precision
variable … might not have been initialized
cannot find symbol / cannot resolve symbol
identifier expected
incompatible types
possible loss of precision
variable … might not have been initialized
Further reading:
- Variable (computer science) available at http://en.wikipedia.org/wiki/Variable_(computer_science)
- Naming convention (programming) available at http://en.wikipedia.org/wiki/Naming_convention_(programming)
- Java Code Conventionsavailable at www.oracle.com/technetwork/java/codeconventions-150003.pdf