Java Reference
In-Depth Information
each with unique types of parameters. For example, the String class has many
different constructors, including one which constructs a new String from a
different String and another that constructs a new String from an array
of bytes.
String strbystr = new String(oldstr);
String strbyarr = new String(myByteArray);
3.2.2.2
One of the most commonly used classes is the String class. It comes already
defined as part of Java and has some special syntax for initialization which
makes it look familiar. Whereas other objects need a new keyword and a con-
structor call, a String object can be created and initialized with the intuitive
double quotes, as in:
Strings
String xyz="this is the stringtext";
The compiler also makes a special allowance for String s with respect to
the plus sign ( + ). It can be used to concatenate two String s into a third, new
String .
String phrase = "That is"
String fullsent = phrase + " all.";
It is worth noting that String s do not change—they are immutable .
When you assign a String the value of one String plus another, there's a lot
of String object creation going on behind the scenes. If you need to do a lot
of concatenation of String s, say inside loops, then you should look into the
use of the StringBuffer object. See Appendix A of Thinking in Java , 3rd ed.,
the section titled Overloading “+” and the StringBuffer , for a full discussion
of the tradeoffs here.
There are a variety of methods for String —ones that will let you make
substrings, search for substrings at the start or end or anywhere in the string,
or check for equality of two strings.
Table 3.2 shows some of the most useful methods associated with String
objects.
Search WWH ::




Custom Search