📜  用示例编写Java中的 toString() 方法

📅  最后修改于: 2022-05-13 01:54:24.903000             🧑  作者: Mango

用示例编写Java中的 toString() 方法

Java中Writer类的toString()方法用于获取这个Writer实例的String表示。此方法不接受任何参数并返回所需的 String 值。

句法:

参数:此方法接受不接受任何参数。

返回值:此方法返回一个字符串值,它是 Writer 实例的字符串表示形式。

下面的方法说明了 toString() 方法的工作:

方案一:

// Java program to demonstrate
// Writer toString() method
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
  
            // Create a Writer instance
            Writer writer
                = new PrintWriter(System.out);
  
            // Get the String
            // to be written in the stream
            String string = "GeeksForGeeks";
  
            // Write the the string
            // to this writer using write() method
            writer.write(string);
  
            System.out.println("String representation: "
                               + writer.toString());
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
String representation: java.io.PrintWriter@232204a1

方案二:

// Java program to demonstrate
// Writer toString() method
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
  
        try {
  
            // Create a Writer instance
            Writer writer
                = new PrintWriter(System.out);
  
            // Get the String
            // to be written in the stream
            String string = "GFG";
  
            // Write the the string
            // to this writer using write() method
            writer.write(string);
  
            System.out.println("String representation: "
                               + writer.toString());
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
String representation: java.io.PrintWriter@232204a1