toString() 和 new String()用法区别

@[TOC](toString() 和 new String()用法区别)
本文讨论的是在加密解密的过程中其2者使用的区别

先上源码

/**      * <p>      * The {@code toString} method for class {@code Object}      * returns a string consisting of the name of the class of which the      * object is an instance, the at-sign character `{@code @}', and      * the unsigned hexadecimal representation of the hash code of the      * object. In other words, this method returns a string equal to the      * value of:      * <blockquote>      * <pre>      * getClass().getName() + '@' + Integer.toHexString(hashCode())      * </pre></blockquote>      *      * @return  a string representation of the object.      */public StringtoString(){returngetClass().getName()+"@"+ Integer.toHexString(hashCode());}

toString() 和 new String()用法区别
getClass().getName() + ‘@’ + Integer.toHexString(hashCode())
通俗的说:toString()返回的是其实例类名+@+对象的哈希码

继续上源码

如何插入一段漂亮的代码片

博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的代码片.

/**      * Constructs a new {@code String} by decoding the specified array of bytes      * using the platform's default charset.  The length of the new {@code      * String} is a function of the charset, and hence may not be equal to the      * length of the byte array.      *      * <p> The behavior of this constructor when the given bytes are not valid      * in the default charset is unspecified.  The {@link      * java.nio.charset.CharsetDecoder} class should be used when more control      * over the decoding process is required.      *      * @param  bytes      *         The bytes to be decoded into characters      *      * @since  JDK1.1      */publicString(byte bytes[]){this(bytes,0, bytes.length);}

toString() 和 new String()用法区别
通俗的说:new String()返回的是一串通过平台默认字符集解码后得到的字符串且长度可能会与原字符串不等

举个例子:

@TestpublicvoidTest()throwsException{String str="TU0jV0xBTiNVYys5bEdiUjZlNU45aHJ0bTdDQStBPT0jNjQ2NDY1Njk4IzM5OTkwMDAwMzAwMA==";String rlt1=newString(Base64.decode(str));String rlt2=Base64.decode(str).toString();System.out.println(rlt1);System.out.println(rlt2);}

toString() 和 new String()用法区别
那什么时候用什么方法呢?

new String()一般使用字符转码的时候,byte[]数组的时候用

toString()对象打印的时候使用