将对象转换为字符串的Java程序
第一个字节需要转换为对象字节,可以轻松处理以转换为字符串。使用 Object 类的toString()方法或 String.valueOf(object) 方法在Java中将 Object 转换为 String。由于Java中的类主要有两种,即用户自定义类和预定义类,如StringBuilder或StringBuffer,其对象可以转换为字符串。
方法:
- 将用户定义的类对象转换为字符串
- 将StringBuilder (预定义类)对象转换为 String
方法 1:使用 toString() 方法或String.valueOf(object_name) 方法。
Java
// Java Program to convert pre defined class object
// (Helper class) to string using value() method
class GFG {
// Main driver method
public static void main(String[] args)
{
// Object of helper class
Helper help = new Helper();
// converting object to string
// using toString() method
String s1 = help.toString();
// converting object to string
// using valueOf() method
String s2 = String.valueOf(help);
// Printing the converted string
System.out.println(
"Converted string object || using toString() Method: " + s1);
// Printing the converted string
System.out.println(
"Converted string object || using valueOf() Method: " + s2);
}
}
class Helper {
// To make class object in main
}
Java
// Java Program to convert StringBuilder object to string
class GFG {
// Main driver method
public static void main(String[] args)
{
/* String taken for consideration */
String s = "Geeks For Geeks";
// Passing string s to StringBuilder class object
StringBuilder sb = new StringBuilder(s);
// Converting the object to string
// Converting StringBuilder to string
String objToString = sb.toString();
// Printing the strings to verify
System.out.println("String: " + s);
System.out.println("Converted String: "
+ objToString);
}
}
输出
Converted string object || using toString() Method: Helper@214c265e
Converted string object || using valueOf() Method: Helper@214c265e
方法 2:将StringBuilder (预定义类)对象转换为 String。
Java中的 StringBuilder 表示可变的字符序列。由于Java中的 String Class 创建了一个不可变的字符序列,StringBuilder 类提供了 String Class 的替代方案,因为它创建了一个可变的字符序列。
类层次结构:
java.lang.Object
↳ java.lang
↳ Class StringBuilder
例子:
Java
// Java Program to convert StringBuilder object to string
class GFG {
// Main driver method
public static void main(String[] args)
{
/* String taken for consideration */
String s = "Geeks For Geeks";
// Passing string s to StringBuilder class object
StringBuilder sb = new StringBuilder(s);
// Converting the object to string
// Converting StringBuilder to string
String objToString = sb.toString();
// Printing the strings to verify
System.out.println("String: " + s);
System.out.println("Converted String: "
+ objToString);
}
}
输出
String: Geeks For Geeks
Converted String: Geeks For Geeks