The usage difference between toString() and new String ()

The usage difference between toString() and new String ()

TestString.java

package com.atguigu;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

/**
 * TestString
 *    toString 和 new String 原理和区别
 */
public class TestString {
    public static void main(String[] args) {
        // 表示密文
        String str="TU0jV0xBTiNVYys5bEdiUjZlNU45aHJ0bTdDQStBPT0jNjQ2NDY1Njk4IzM5OTkwMDAwMzAwMA==";
        // 使用base64进行解码
        String rlt1=new String(Base64.decode(str));
        // 使用base64进行解码
        String rlt2=Base64.decode(str).toString(
        );

        System.out.println("new String===" + rlt1);

        System.out.println("toString==" + rlt2);
    }
}



Which one is correct? why?

The new String() method should be used here, because Base64 encryption and decryption is a principle of converting the encoding format

The usage difference between toString() and new String ()

str.toString is the toString method of the class that called this object. Usually such a String is returned  : [class name]@[hashCode]

new String(str) is a byte array based on parameter, using the default encoding format of the java virtual machine to decode this byte array into the corresponding character. If the default encoding format of the virtual machine is ISO-8859-1 , the characters corresponding to the bytes can be obtained according to the ascii encoding table.

When to use what method?

When new String() generally uses character transcoding, when byte[] array

toString() used when printing the object

Guess you like

Origin blog.csdn.net/qq_39368007/article/details/114530115
Recommended