Boolean, numeric, character, and String variables & fields.
Java is a strongly- and statically-typed language:
All variables must be declared with a type. (Starting in Java 10, the type of some variables can be inferred, but that inference is done at compile time—effectively putting the inferred type into the bytecode, as if it had been declared explicitly.)
The type of a variable cannot change after declaration.
We can only assign values to that variable if the value is assignment-compatible with that variable. For example, a byte
, short
, or char
value may be assigned to an int
, but not the reverse.
When typing (or copying and pasting) any of the examples on this page into JShell, the comment portion—starting with the two slashes (//
) and continuing to the end of the line—may be omitted.
Some of the literal values in the examples are rendered in different colors; these simply reflect the code syntax highlighting library’s understanding (or, in some cases, misunderstanding) of proper Java syntax. When these examples are typed or pasted into JShell, the colors seen on this page will not be displayed by JShell.
Variables may be declared at various levels, listed here from the lowest to highest level:
In compound statements, formed by a pair of braces enclosing zero or more statements.
A compound statement is typically used for the body of a flow-control statement—a conditional, iteration, or exception handling statement; however, in Java, a compound statement may be used almost any place where a simple statement can be used. A variable declared within a compound statement is not visible/accessible outside the the braces enclosing the compound statement; if the compound statement is re-entered (e.g. in an iteration statement), any such variable is considered to be re-declared, and will not retain its value from the previous execution of the compound statement.
A variable declared in a compound statement is lexically scoped—that is, it is visible after the point of declaration until the end of the compound statement. Also, if there are nested compound statements, and a variable is declared in an outer compound statement, a variable with the same name may not be declared in an inner compound statement that follows the original declaration.
In initialization section of a for
statement.
A basic for
statement may include declaration-with-assignment of zero or more variables in the initialization section. These variables are visible in the condition and update sections, and in the statement (usually a compound statement) forming the body of the for
statement.
Within methods or constructors.
A variable declared with method scope is defined only within that method: it is not visible outside the method, and it does not retain its value across invocations of the method.
A variable declared in a method is lexically scoped: it is visible after the point of declaration until the end of the method.
If a variable is declared with method scope, no variable with the same name may be declared in a compound statement following the variable declaration, within the same method.
In a class
(including an enum
) or interface
.
A variable may be declared as a member of a class; usually, we refer to a variable declared at this level as a field, though we also use the terms instance variable (for a non-static
field), and class variable or static variable (for a static
field).
A variable declared at this level maintains its value (though that value may be modified as the code executes) for the lifetime of the instance of the class, if non-static
. A static
field maintains its value from the moment the class is initialized until the class is unloaded from memory (typically when the application terminates).
A variable declared at this level (i.e. a field) does not prevent us from declaring a variable (or parameter) with the same name in a method of a class, or in a compound statement within a method. In the lower scope, the local variable hides (or shadows) the variable at the class level. We can still access the field, but we have to qualify the reference to it with the this
keyword (for a non-static
field) or the class name (for a static
field).
The only type of variable we can declare in an interface is implicitly public static final
—that is, a public
constant—so it only has one value (assigned in the definition of the interface), which must be a compile-time constant expression (in other words, either a literal value, or an expression involving literals and/or other compile-time constants).
Field, variables, and parameters (which we can think of as local variables in a method or constructor, which are assigned a value on invocation) are always declared with the type, followed by the variable name. For example, a variable named running
, of the boolean
type, would be declared as
boolean running;
We can also assign a value along with the declaration (a declaration-with-assignment statement):
boolean running = false;
Fields (variables declared as members of a class
, enum
, or interface
) typically have modifiers that precede the type in the declaration.1
There are very few constraints—but several important conventions—on how we name variables. First, let’s look at the rules enforced by the compiler:
A variable name—and any other identifier we declare in Java—must consist of at least one character (yes, that rule is rather trivial).
An identifier can only begin with a letter, an underscore (_
), or the dollar sign ($
). For these purposes, “letters” actually includes not just a
through z
and A
through Z
, but any Unicode character that has the “Alphabetic” property.
After the first character of the identifier name, digits are also allowed. Again, this is based on Unicode distinctions, not just the Latin alphabet.
Now to the conventions. These are long-established and widely accepted conventions, originating in common C practice, formalized in Sun’s (now Oracle’s) “Code Conventions for the Java™ Programming Language, and further codified in the Google Java Style Guide and many other organizations’ style guides.
Variables (but not constants, which we won’t address here) are named using lowerCamelCase
.
Variable names only use ASCII letters and digits.
Variable names are typically given noun or noun phrase names—except for boolean
(or Boolean
) variables, which are generally adjectives or adjective phrases.
It is neither necessary nor desirable to have special prefixes or suffixes on variable names (m
at the start of private
members of a class, i
as a prefix for integer-valued variables, etc.). Instead, long-lived variable names should be given short but meaningful names from the domain of the application, while short-lived local variables (e.g. loop counters) can be given simple, common names for that purpose (e.g. i
, j
, row
, column
).
(Another convention that helps here is declaring variables at the lowest practical scope.)
At DDC, we add a few more rules for bootcamp students, based on the instructors’ experience in developing and maintaining software:
Variables referring to scalar quantities or single non-collection objects are given singular noun or noun phrase names.
Variables referring to arrays, collections, etc. are given plural or collective noun or noun phrase names.
Acronyms, initialisms, and other abbreviations should be avoided, unless a given abbreviation is widely recognized and used, and is significantly shorter than the full word or phrase being abbreviated.
boolean running; // Conforms with compiler requirements, and with Sun/Oracle and Google
// conventions.
boolean running = 0; // Conforms with compiler variable naming requirements, but DOES NOT
// compile, because we are assigning a non-boolean value to a boolean
// variable.
boolean running = false; // Conforms with requirements & conventions, and compiles successfully.
String headline; // Conforms with compiler requirements, and with Sun/Oracle and Google
// conventions.
String _headline; // Conforms with compiler requirements, BUT NOT with Sun/Oracle and Google
// conventions.
String $headline; // Conforms with compiler requirements, BUT NOT with Sun/Oracle and Google
// conventions.
String headline = "User Stories"; // Conforms with requirements & conventions, and compiles
// successfully.
String headline = 'U'; // Conforms with naming requirements & conventions, but DOES NOT compile,
// because the literal value is a char.
String headline = 100; // Conforms with naming requirements & conventions, but DOES NOT compile,
// because the literal value is an int.
int height; // Conforms with compiler requirements, and with Sun/Oracle and Google conventions.
int height = 168; // Conforms with requirements & conventions, and compiles successfully.
int height = 168.0; // Conforms with naming requirements & conventions, but DOES NOT compile,
// because the literal value is a double.
int height = 168f; // Conforms with naming requirements & conventions, but DOES NOT compile,
// because the f type suffix makes the literal value a float.
int height = "168"; // Conforms to the naming requirements & conventions, but DOES NOT compile,
// because the literal value is a String.
For more information, see “Classes in Java”. ↩