对于我这种用惯了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()方法。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有