首页 > 编程语言 > 详细

Java字符串一个比较有趣的问题

时间:2014-03-31 18:23:11      阅读:496      评论:0      收藏:0      [点我收藏+]

给大家看一个比较有趣的代码:

package com.crazyit;

public class Student {
	public static void main(String[] args) {
		Object he = new Student();
		String str = "hello";
		str += he;
		System.out.println(str);
	}
}
运行结果如下:

bubuko.com,布布扣

但是如果改为这样:

package com.crazyit;

public class Student {
	public static void main(String[] args) {
		Object he = new Student();
		String str = "hello";
		he += str;
		System.out.println(he);
	}
}
运行显示如下:

bubuko.com,布布扣

为什么会出现这样的情况,

因为对于第一个程序,+=左边的变量类型是String,所以he将自动转换为String(就是使用它的toString()返回值),Object是String的父类

而对第2个程序,+=左边的变量类型不是String类型,所以产生错误。


下面再看一个程序:

package com.crazyit;

public class Student {
	public static void main(String[] args) {
		Object he = new Student();
		String str = "hello";
		he = he + str;
		System.out.println(he);
	}
}
运行结果如下:

bubuko.com,布布扣

因为此时系统自动将he转换为String类型后与str连接进行运算。

Java字符串一个比较有趣的问题,布布扣,bubuko.com

Java字符串一个比较有趣的问题

原文:http://blog.csdn.net/litianpenghaha/article/details/22671501

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!