A variable is a name that has a value. A variable can have different
values at different times.
All variables must be declared. When a variable
is declared, it is given a type that tells what kind
of values it can have. It may also be given an initial value. An int
variable can only have an integer value, a String variable can
only have a character string as its value, and so on.
Java is case-sensitive; that is, result, Result,
and RESULT are three different variables. Type names must be
capitalized correctly: int, not Int; String,
not string; etc.
- An instance variable is one that is declared in a class
but a separate copy of it is "owned" by each individual instance,
or object, of that class.
- A class variable, or static variable, is declared in a class
using the keyword static. There is only one of it,
and it is considered to be "owned" by the class itself, not by individual
objects.
- A local variable is one that is declared within a method.
It is available only within that method.
There are strict conventions for variable names:
- Names are almost never abbreviated: Use
employee rather than
emp; use yearEndBonus rather than yebonus.
(However, very common abbreviations can be used, such as max
and min.)
- Variable names always begin with a lowercase letter.
- If a name consists of multiple words, the first letter of all words except
the first is capitalized, for example,
endOfLineMarker, totalBill.
(This is sometimes called "camelCase.")
- Although legal, variable names never contain the underscore (unless they
are constants) or the dollar sign.
Many kinds of things in Java have names, not just variables. Proper naming and
capitalization helps the experienced Java programmer know what kind of thing is
being named. The names of classes and interfaces
always begin with a capital letter, and constants
are written using all capitals, with underscores to separate words.