Role of toString() in Java

Asked 1 years ago, Updated 1 years ago, 100 views

/*
 * A program to erase the - in the middle of the following resident registration number and fill in the blank to print it out
 * Let's write it down. However, frequent string generation occurs by utilizing the StringBuilder class
 * You should try not to. 990925-1012999
 */

package ch11;

public class Ch11_2_Q1 {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("990925-1012999");
        sb.replace(6, 7, " ");
        System.out.println(sb.toString());
    }
}

I'm solving the above example shown in the comments, but I don't understand the toString().

Even if the output part is System.out.println(sb); you can get the same result, but you can't output the variable as it is What is the difference between outputting using toString()?

java tostring eclipse

2022-09-22 20:04

1 Answers

Java is an object-oriented language.

The best class in Java is Object and toString is implemented.

The output of the object also returns the result of the toString method.

In all classes, the object is the top parent, so toString is unconditionally implemented.

StringBuilder is overriding toString internally.

This means that you use StringBuilder and explicitly call the object.toString() or substitute the object and print it out.


2022-09-22 20:04

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.