IDs and variables
From our school days, we have an intuitive understanding of what a variable is. We think of it as a name that represents a value. We solve problems using such variables as x gallons of water or n miles of distance, and similar. In Java, the name of a variable is called an ID and can be constructed by certain rules. Using an ID, a variable can be declared (defined) and initialized.
ID
According to the Java Language Specification (https://docs.oracle.com/javase/specs), an ID (a variable name) can be a sequence of Unicode characters that represent letters, digits 0-9, a dollar sign ($
), or an underscore (_
).
Other limitations are outlined here:
- The first symbol of an ID cannot be a digit.
- An ID cannot have the same spelling as a keyword (see the Java keywords section of Chapter 3, Java Fundamentals).
- It cannot be spelled as a
true
orfalse
Boolean literal or as anull
literal. - And since Java 9, an ID cannot be just an underscore (
_
).
Here are a few unusual but legal examples of IDs:
$
_42
αρετη
String
Variable declaration (definition) and initialization
A variable has a name (an ID) and a type. Typically, it refers to the memory where a value is stored, but may refer to nothing (null
) or not refer to anything at all (then, it is not initialized). It can represent a class property, an array element, a method parameter, and a local variable. The last one is the most frequently used kind of variable.
Before a variable can be used, it has to be declared and initialized. In some other programming languages, a variable can also be defined, so Java programmers sometimes use the word definition as a synonym of declaration, which is not exactly correct.
Here is a terminology review with examples:
int x; //declaration of variable x
x = 1; //initialization of variable x
x = 2; //assignment of variable x
Initialization and assignment look the same. The difference is in their sequence: the first assignment is called initialization. Without an initialization, a variable cannot be used.
Declaration and initialization can be combined in a single statement. Observe the following, for example:
float $ = 42.42f;
String _42 = "abc";
int αρετη = 42;
double String = 42.;
var type holder
In Java 10, a sort of type holder, var
, was introduced. The Java Language Specification defines it thus: “var is not a keyword, but an identifier with special meaning as the type of a local variable declaration.”
In practical terms, it lets a compiler figure out the nature of the declared variable, as follows (see the var()
method in the com.packt.learnjava.ch01_start.PrimitiveTypes
class):
var x = 1;
In the preceding example, the compiler can reasonably assume that x
has the int
primitive type.
As you may have guessed, to accomplish that, a declaration on its own would not suffice, as we can see here:
var x; //compilation error
That is, without initialization, the compiler cannot figure out the type of the variable when var
is used.