Java Reference
In-Depth Information
ȗ
What type should you use for the variable?
ȗ
What name should you give the variable?
The type depends on the intended use. If you need to store a string, use the
String
type for your variable.
It is an error to store a value whose class does not match the type of the variable. For
example, the following is an error:
String greeting = 13;
// ERROR: Types don't match
You cannot use a
String
variable to store an integer. The compiler checks type
mismatches to protect you from errors.
When deciding on a name for a variable, you should make a choice that describes the
purpose of the variable. For example, the variable name
greeting
is a better choice
than the name
g
.
Identifiers for variables, methods, and classes are composed of letters, digits, and
underscore characters.
An identifier is the name of a variable, method, or class. Java imposes the following
rules for identifiers:
ȗ
Identifiers can be made up of letters, digits, and the underscore (_) and dollar
sign ($) characters. They cannot start with a digit, though. For example,
greeting1
is legal but
1greeting
is not.
ȗ
You cannot use other symbols such as? or
%
. For example,
hello!
is not a
legal identifier.
ȗ
Spaces are not permitted inside identifiers. Therefore,
lucky number
is not
legal.
ȗ
Furthermore, you cannot use reserved words, such as
public
, as names; these
words are reserved exclusively for their special Java meanings.