Special Operator Support for Strings

   

Before leaving the subject of operators, it is important to cover a special use of the addition operator as it relates to the String class discussed later in Chapter 8, "Using Strings and Text."

In general, Java, unlike C++, does not support operator overloading. There is one exception, however. Java does allow the concatenation of String objects using the + and += operators. The behavior of these operators with String objects is just what you would expect if you are familiar with C++. The String operands are concatenated to produce a new String that contains the values of both. In the following expression, the resulting string would be "Hello World":

 "Hello" + " World" 

If one of the operands used with these operators is not a String, its string representation is implicitly obtained and used in the expression. This means, for example, that a numeric value can be added to a String. The numeric value is converted to an appropriate sequence of characters , which are concatenated to the original String. All the following are legal concatenations:

 "Wizard" + " of " + "Oz" "Emily's birthday is " + "December " + 19 "Answer is: " + true 

Note

This might seem like a contradiction that Java does not allow you to overload operators, yet it provides such support as a built-in feature for String s. Although viewed as a powerful feature in C++, operator overloading can make code difficult to read because it is not always obvious when an operator in an expression is tied to a class method. The use of overloaded operators also adds to the maintenance required for a class because each such method must be updated whenever attributes are added to or removed from a class. Java made an exception for the String class because almost every program you write will require simple manipulation of text like that supported by these operators.


   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net