To create a variable, you must tell Java the type and the name of the variable. Creating a variable is also called declaring a variable.
To declare (create) a variable, you will specify the type, leave at least one space, then the name for the variable and end the line with a semicolon (;
). Java uses the keyword int for integer, double for a floating-point number (a double-precision number), and boolean for a boolean value (true or false).
Note: the Java language, like all other computer languages, consists of a set of keywords. int, double, and boolean are among these keywords. Java syntax is case-sensitive. These keywords should be spelled in lowercase. This is not a convention but a syntactic rule.
Here is an example declaration of a variable of type integer, called score:
int score;
Think of the semicolon in Java as being similar to a period (.
) in English. The period is how you show the end of an English sentence. In Java you use a semicolon (;
) to show the end of a statement.
You can also optionally specify an initial value (initialization) for the variable by adding an equals sign =
followed by the value.
int score = 4;
Run the following code to see what is printed.
The equal sign here =
doesn’t mean the same as it does in a mathematical equation where it implies that the two sides are equal. Here it means to set the value in the memory location (box) associated with the name on the left to a copy of the value on the right. The first line above sets the value in the box called score to 4. Also, note that the variable has to be on the left-hand side (LHS) of the =
, and the value on the right-hand side (RHS). Switching the two is called assignment dyslexia.
Another way to say is, the = sign does not denote equality; it is the assignment operator. The assignment operator assigns the value on the right-hand side (RHS) of the operator, to the variable on the left-hand side (LHS) of the operator.