Java Reference
In-Depth Information
includes the space between the first and last names. Some methods do not return a
value. Other String methods are discussed in the next section.
The act of declaring the object reference variable and creating the object itself
can be combined into one step by initializing the variable in the declaration, just
as we do with primitive types:
String title = new String("Java Software Solutions");
Even though they are not primitive types, character strings are so fundamental
and so often used that Java defines string literals delimited by double quotation
marks, as we've seen in various examples. This is a shortcut notation. Whenever
a string literal appears, a String object is created automatically. Therefore the
following declaration is valid:
String city = "London";
That is, for String objects, the explicit use of the new operator and the call to the
constructor can be eliminated. In most cases, we will use this simplified syntax.
Aliases
Because an object reference variable stores an address, a programmer must be
careful when managing objects. First, let's review the effect of assignment on
primitive values. Suppose we have two integer variables, num1 , initialized to 5,
and num2 , initialized to 12:
num1
5
num2
12
In the following assignment statement, a copy of the value that is stored in num1
is stored in num2 :
num2 = num1;
The original value of 12 in num2 is overwritten by the value 5. The variables num1
and num2 still refer to different locations in memory, and both of those locations
now contain the value 5:
num1
5
num2
5
 
Search WWH ::




Custom Search