Just like every entity in the real world has a name, so you need to choose names for the things you will refer to in your program. It's called an identifier.
Rules for naming identifiers:
An identifier is a sequence of characters that consists of letters, digits, underscores '_' and dollar sign $.
An identifier must start with a letter, an underscore or a dollar sign. It cannot start with a digit.
An identifier cannot be a reserved word.
An identifier cannot be true, false or null.
An identifier can be of any length.
Example of legal identifier:
$2, ComputerArea, area, radius
Example of illegal identifier:
2A, d+4
Note: Java is case sensitive. So, area and Area are different identifiers.
Variables are used to store data in a program. Variables are for representing data of a certain type. To use a variable, you declare it by telling the compiler its name as well as what type of data it represents. This variable declaration tells the compiler to allocate appropriate memory space for the variable based on its data type.
The syntax for declaring a variable is:
datatype variableName;
Example:
public class ComputeArea {
public static void main(String[] args) {
double radius; // declare a variable radius
double area; // declare a variable area
System.out.println("Enter the radius: ");
radius = in.nextDouble(); // read the radius
area = radius * radius * 3.14;
System.out.println ("Area for circle with radius " + radius + " is " + area);
}
}
In our ComputeArea program (as above), we declare radius and area as double variables.
Other data types are int, double, char, byte, short, long, float, and boolean.
Since radius and area are the same data type, we can combine the declaration together. For example;
double radius, area;
Note: Variables should be given meaningful names (identifier)
For example, in the ComputeArea program, it is good to use the word 'radius' to represent radius value compared to character 'r'.
Java keywords may not be used as identifiers, eg:
abstract, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, extends, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throws, transient, try, void, volatile, while
The value of a variable may change during the execution of the program, but a constant represents permanent data that never changes.
In our ComputeArea program, we can declare 3.14 as a constant value and we can name it as PI because 3.14 represents Pi value.
Syntax for declaring a constant:
final datatype CONSTANTNAME = VALUE;
Example:
public class ComputeArea {
public static void main(String[] args) {
final double PI = 3.14;
double radius, area;
System.out.println("Enter the radius: ");
radius = in.nextDouble(); // read the radius
area = radius * radius * PI;
System.out.println ("Area for circle with radius " + radius + " is " + area);
}
}