Java Reference
In-Depth Information
may not assign a
String
object to it before you use the variable — then you must initialize it to a special
null
value:
String anyString = null; // String variable that doesn't reference a string
The literal
null
is an object reference value that does not refer to anything. Because an array is essentially
an object, you can also use
null
as the value for an array variable that does not reference anything.
You can test whether a
String
variable refers to anything or not by a statement such as:
if(anyString == null) {
System.out.println("anyString does not refer to anything!");
}
The variable
anyString
continues to be
null
until you use an assignment to make it reference a partic-
ular string. Attempting to use a variable that has not been initialized is an error. When you declare a
String
variable, or any other type of variable in a block of code without initializing it, the compiler can detect any
attempts to use the variable before it has a value assigned and flags it as an error. As a rule, you should al-
ways initialize variables as you declare them.
You can use the literal
null
when you want to discard a
String
object that is currently referenced by a
variable. Suppose you define a
String
variable like this:
String message = "Only the mediocre are always at their best";
A little later in the program, you want to discard the string that
message
references. You can just write
this statement:
message = null;
The value
null
replaces the original reference stored so
message
now does not refer to anything.
Arrays of Strings
You can create arrays of strings. You declare an array of
String
objects with the same mechanism that you
used to declare arrays of elements for the basic types. You just use the type
String
in the declaration. For
example, to declare an array of five
String
objects, you could use the statement:
String[] names = new String[5];
It should now be apparent that the argument to the method
main()
is an array of
String
objects because
the definition of the method always looks like this:
public static void main(String[] args) {
// Code for method...
}
You can also declare an array of
String
objects where the initial values determine the size of the array:
String[] colors = {"red", "orange", "yellow", "green",
"blue", "indigo", "violet"};