对于我这种用惯了C++的人来说,突然见到有人写java程序的时候竟然将整数和String类型的变量使用+连接到一起,感到非常奇怪,追究了下原因。
原来所有的java对象都有toString()方法,而某些时候这个方法会自动被调用的。
1 class toString_test
2 {
3 public static void main(String[] args)
4 {
5 int year=2015;
6 int month=9;
7 String str="now is ";
8 str=str+year+"."+month;
9 System.out.println(str);
10 }
11 }
如上述代码中第8行,str=str+year+"."+month;
其实就自动被转换成了str=str+year.toString()+"."+month.toString();
此外像System.out.println(x);如果x是非String 类型的变量,在这里也会自对调用toString()方法。