(^56) | Java Syntax and Semantics, Classes, and Objects
Here, Modifiers are like the modifiers for the class declarations (publicand private), and
Type-Name is the name of a type or class such as charor String. We will introduce addi-
tional modifiers as we need them in later chapters. Note that the modifiers are optional—
we can write a declaration without using any of them. Notice also that a declaration always
ends with a semicolon.
From the syntax template, you can see that we can declare several variables in one
statement:
charletter, middleInitial, ch;
Here, all three variables are declared to be charvariables. Our preference, though, is to de-
clare each variable with a separate statement:
charletter;
charmiddleInitial;
charch;
Declaring each variable with a separate statement allows you to attach comments to the
right of each declaration. For example:
String firstName; // A person’s first name
String lastName; // A person’s last name
String title; // A person’s title, such as Dr.
charmiddleInitial; // A person’s middle initial
charmyChar; // A place to store one letter
These declarations tell the compiler to reserve memory space for three Stringvariables—
firstName,lastName, and title—and two charvariables—middleInitialand myChar. The com-
ments explain to someone reading the program what each variable represents.
We saw earlier that the syntax template for a class contains a set of class declarations,
and that some of those declarations can be variables. For example, the following class has two
variable declarations and shows how we might use aprivatemodifier as part of a declaration:
public classSample // The start of a public class called Sample
{
private char myChar; // A private char type variable declared in class Sample
String myString; // A String object variable declared in class Sample
} // The end of class Sample
Now that we’ve seen how to declare variables in Java, let’s look at how to declare constants.
Constants All single characters (enclosed in single quotes) and strings (enclosed in double
quotes) are constants.
‘A’ ‘@’ “Howdy boys” “Please enter an employee number:”