November 24, 2013

Published November 24, 2013 by

Java Variables

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:
  1. Data type
  2. Variable name
  3. Initial value (optional)
  4. 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:


Further reading: