博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JAVA中toString方法
阅读量:7119 次
发布时间:2019-06-28

本文共 2251 字,大约阅读时间需要 7 分钟。

因为它是Object里面已经有了的方法,而所有类都是继承Object,所以“所有对象都有这个方法”。

它通常只是为了方便输出,比如System.out.println(xx),括号里面的“xx”如果不是String类型的话,就自动调用xx的toString()方法

总而言之,它只是sun公司开发java的时候为了方便所有类的字符串操作而特意加入的一个方法

回答补充:

写这个方法的用途就是为了方便操作,所以在文件操作里面可用可不用

例子1:

public class Orc {
public static class A {
public String toString() {
return "this is A"; } } public static void main(String[] args) {
A obj = new A(); System.out.println(obj); } }

如果某个方法里面有如下句子:

A obj=new A();

System.out.println(obj);

会得到输出:this is A

例子2:

public class Orc {
public static class A {
public String getString() {
return "this is A"; } } public static void main(String[] args) {
A obj = new A(); System.out.println(obj); System.out.println(obj.getString()); } }

会得到输出:xxxx@xxxxxxx的类名加地址形式

System.out.println(obj.getString());

会得到输出:this is A

看出区别了吗,toString的好处是在碰到“println”之类的输出方法时会自动调用,不用显式打出来。

1 public class Zhang  2  3 {
4 5 public static void main(String[] args) 6 7 {
8 9 StringBuffer MyStrBuff1 = new StringBuffer(); 10 11 MyStrBuff1.append("Hello, Guys!"); 12 13 System.out.println(MyStrBuff1.toString()); 14 15 MyStrBuff1.insert(6, 30); 16 17 System.out.println(MyStrBuff1.toString()); 18 19 } 20 21 }

值得注意的是, 若希望将StringBuffer在屏幕上显示出来, 则必须首先调用toString方法把它变成字符串常量, 因为PrintStream的方法println()不接受StringBuffer类型的参数.

1 public class Zhang 2 {
3 public static void main(String[] args) 4 {
5 String MyStr = new StringBuffer(); 6 MyStr = new StringBuffer().append(MyStr).append(" Guys!").toString(); 7 System.out.println(MyStr); 8 } 9 }

toString()方法在此的作用是将StringBuffer类型转换为String类型.

1 public class Zhang 2 {
3 public static void main(String[] args) 4 {
5 String MyStr = new StringBuffer().append("hello").toString(); 6 MyStr = new StringBuffer().append(MyStr).append(" Guys!").toString(); 7 System.out.println(MyStr); 8 } 9 }

转载地址:http://rrnel.baihongyu.com/

你可能感兴趣的文章
Spark源码分析之二:Job的调度模型与运行反馈
查看>>
C#——await与async实现多线程异步编程
查看>>
如何找到一个好的Joomla主机提供商
查看>>
Dockerfile最佳实践(二)
查看>>
T-SQL Enhancement in SQL Server 2005[下篇]
查看>>
杀毒软件可能令企业用户陷入更大危机
查看>>
澳政府投资光伏发电 内外资项目角逐高额补助
查看>>
《从问题到程序:用Python学编程和计算》——2.4 字符串
查看>>
《AngularJS实战》——3.2 过滤器的应用
查看>>
《贝叶斯思维:统计建模的Python学习法》——2.5 封装框架
查看>>
《Cisco安全防火墙服务模块(FWSM)解决方案》——2.7 软件架构
查看>>
《R与Hadoop大数据分析实战》一2.6 小结
查看>>
微软重写 Windows 10 激活规则
查看>>
程序员的生存技巧 —— 搜索技巧
查看>>
《Scala机器学习》一一
查看>>
《版式设计——日本平面设计师参考手册》—第1章段落样式和字符样式的基础知识...
查看>>
为什么说选择正确的编程语言很重要,以及如何正确的选择
查看>>
2016 年:勒索病毒造成损失预估超过 10 亿美元
查看>>
UC:我们是怎么做出 Chromium M35 内核浏览器
查看>>
《Windows 8 权威指南》——1.3 引入全新内核休眠模式,实现“瞬间开机”
查看>>