什么时候用什么方法呢?
new String()一般使用字符转码的时候,byte[]数组的时候
toString()将对象打印的时候使用
toString()与new String ()用法区别
str.toString是调用了b这个object对象的类的toString方法。一般是返回这么一个String:[class name]@[hashCode]。
new String(str)是根据parameter是一个字节数组,使用java虚拟机默认的编码格式,将这个字节数组decode为对应的字符。若虚拟机默认的编码格式是ISO-8859-1,按照ascii编码表即可得到字节对应的字符。
举个例子:
Base64.Decoder decoder = Base64.getDecoder();
Base64.Encoder encoder = Base64.getEncoder();
String text = "梁天祥的lol账号已经从铂金掉到了黄金一了。";
byte[] textByte = text.getBytes("UTF-8");
//编码
String encodedText = encoder.encodeToString(textByte);
System.out.println("Base64的编码结果为:"+encodedText);
//解码
System.out.println("Base64的new String解码结果为:"+new String(decoder.decode(encodedText), "UTF-8"));
System.out.println("Base64的toString解码结果为:"+decoder.decode(encodedText).toString());
结果:
Base64的编码结果为:
5qKB5aSp56Wl55qEbG9s6LSm5Y+35bey57uP5LuO6ZOC6YeR5o6J5Yiw5LqG6buE6YeR5LiA5LqG44CC
Base64的new String解码结果为:
梁天祥的lol账号已经从铂金掉到了黄金一了。
Base64的toString解码结果为:[B@668bc3d5