13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

60Chapter 3An Experienced Programmer’s Introducti<strong>on</strong> to Javaeach with unique types of parameters. For example, the String class has manydifferent c<strong>on</strong>structors, including <strong>on</strong>e which c<strong>on</strong>structs a new String from adifferent String and another that c<strong>on</strong>structs a new String from an arrayof bytes.String strbystr = new String(oldstr);String strbyarr = new String(myByteArray);3.2.2.2 StringsOne of the most comm<strong>on</strong>ly used classes is the String class. It comes alreadydefined as part of Java and has some special syntax for initializati<strong>on</strong> whichmakes it look familiar. Whereas other objects need a new keyword and a c<strong>on</strong>structorcall, a String object can be created and initialized with the intuitivedouble quotes, as in:String xyz="this is the stringtext";The compiler also makes a special allowance for Strings with respect tothe plus sign (+). It can be used to c<strong>on</strong>catenate two Strings into a third, newString.String phrase = "That is"String fullsent = phrase + " all.";It is worth noting that Strings do not change—they are immutable.When you assign a String the value of <strong>on</strong>e String plus another, there’s a lotof String object creati<strong>on</strong> going <strong>on</strong> behind the scenes. If you need to do a lotof c<strong>on</strong>catenati<strong>on</strong> of Strings, say inside loops, then you should look into theuse of the StringBuffer object. See Appendix A of Thinking in Java, 3rd ed.,the secti<strong>on</strong> titled Overloading “+” and the StringBuffer, for a full discussi<strong>on</strong>of the tradeoffs here.There are a variety of methods for String—<strong>on</strong>es that will let you makesubstrings, 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 Stringobjects.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!