字符串操作符+和+=
这个操作符在Java中有一项特殊用途:连接不同的字符串。
这一点已经在前面的例子中展示过了。
尽管与+和+=的传统使用方式不太一样,但是我们还是很自然地使用这些操作符来做这件事情。
这项功能用在C++中似乎是个不错的注意,所以引入了操作符重载(operator overloading)机制,
以便C++程序员可以为几乎所有操作符增加功能
但非常遗憾,与C++的另外一些限制结合在一起,使得操作符重载成为了一种非常复杂的特性,
程序员在设计自己的类时必须对比有非常周全的考虑。
与C++相比,尽管操作符重载在Java中更易实现(就像在C#语言中所展示的那样,它具有相当简单直接的操作符重载机制),但仍然过于复杂。
所以Java程序员不能像C++和C#程序员哪呀那个实现自己的重载操作符。
//: operators/StringOperators.java
import static net.mindview.util.Print.*;
public class StringOperators {
public static void main(String[] args) {
int x = 0, y = 1, z = 2;
String s = "x, y, z ";
print(s + x + y + z);
print(x + " " + s); // Converts x to a String
s += "(summed) = "; // Concatenation operator
print(s + (x + y + z));
print("" + x); // Shorthand for Integer.toString()
}
} /* Output:
x, y, z 012
0 x, y, z
x, y, z (summed) = 3
0
*///:~
请注意,第一个打印语句的输出是012而不是3,而3正是将这些整数求和之后应该得到的结果,
之所以出现这种情况,是因为Java编译器会将x、y和z转换成它们的字符串形式,
然后连接这些字符串,而不是先把它们加到一起。
第二个打印语句把先导的变量转换为String,因此这个字符串转换将不依赖于第一个变量的类型。
最后可以看到使用+=操作符将一个字符串追加到了s上,并且使用了括号来控制表达式的赋值顺序,
以使得int类型的变量在显示之前确实进行了求和操作。
请注意main()中的最后一个示例:有时会看到这种一个空的String后面跟随+和一个基本类型变量,
以此作为不调用更加麻烦的显式方法(在本例中应该是Interger.toString())而执行字符串转换的方式。