更新時間:2019-09-16 10:44:17 來源:動力節點 瀏覽2954次
今天動力節點java培訓機機構小編為各位小伙伴們介紹“java中的tostring方法的作用”,希望通過此文大家能夠掌握ostring方法的作用,下面就隨小編一起看看tostring方法的作用。
因為它是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”之類的輸出方法時會自動調用,不用顯式打出來。
public class Zhang
{
public static void main(String[] args)
{
StringBuffer MyStrBuff1 = new StringBuffer();
MyStrBuff1.append("Hello, Guys!");
System.out.println(MyStrBuff1.toString());
MyStrBuff1.insert(6, 30);
System.out.println(MyStrBuff1.toString());
}
}
值得注意的是, 若希望將StringBuffer在屏幕上顯示出來, 則必須首先調用toString方法把它變成字符串常量,因為PrintStream的方法println()不接受StringBuffer類型的參數.
public class Zhang
{
public static void main(String[] args)
{
String MyStr = new StringBuffer();
MyStr = new StringBuffer().append(MyStr).append(" Guys!").toString();
System.out.println(MyStr);
}
}
toString()方法在此的作用是將StringBuffer類型轉換為String類型.
public class Zhang
{
public static void main(String[] args)
{
String MyStr = new StringBuffer().append("hello").toString();
MyStr = new StringBuffer().append(MyStr).append(" Guys!").toString();
System.out.println(MyStr);
}
}
以上就是動力節點java培訓機構小編介紹的“java中的tostring方法的作用”的內容,希望對大家有幫助,更多java最新資訊請繼續關注動力節點java培訓機構官網,每天會有精彩內容分享與你。
相關免費視頻教程推薦
java語言基礎教程下載——toString()方法:http://www.dabaquan.cn/xiazai/2584.html
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習