Java Reference
In-Depth Information
Let's review the following statement:
String localText = "Some text";
First, a String object containing the text “Some text” was created by the com-
piler. Then, the object reference variable localText was created and adjusted to ref-
erence that object. The compiler handles all this automatically because it treats
String variables in a special way. Whenever the compiler sees a double quoted con-
stant, it will automatically make sure that a String object has been created.
The String class, part of the Java runtime, actually maintains a pool of String s
with unique values. So the first time the runtime sees a literal string or a string-val-
ued constant expression, the String class will check an internal pool of previously
created String s. If one is found, then that String will be used. Otherwise, a new
one will be created and added to the internal pool. In either case, the compiler will
make sure a String object is created for your program when you use the previously
mentioned syntax.
This runtime optimization helps conserve memory utilization and improve per-
formance for commonly used strings. However, in most cases you, as a Java devel-
oper, should not be concerned with, or code in a manner that is dependant on, these
details, since the String class encapsulates this optimization in proper OO fashion.
C OMPARING S TRINGS
The base Object class contains many useful methods. Since the String class inherits
from Object , every String object you create will contain these methods as well. One
example is a method called equals() that will compare two String s for equality:
Return type
Method name
Parameter signature
boolean
equals
(Strings)
A Java statement can use this method to compare the text value in a String ob-
ject (such as localText ) to some other String object:
if (localText.equals ("Some other text")) {
...
}
 
Search WWH ::




Custom Search