开发者

Java getBytes()

Do you know the problem as to why i am not getting Hello

byte f []  ="hello".getBytes();

Sys开发者_JS百科tem.out.println(f.toString());


Because byte[]#toString() is (usually) not implemented as new String(byteArray), which would lead to the result you expect (e.g. System.out.println(new String(byteArray));.

You may want to give this page an eye...


Because the toString method of a byte array does not print its contents (at all). And bytes are not characters anyway. Why do you expect to see "hello"? Why not doing System.out.println("hello") directly?


The reason you are getting "strange" output from System.out.println(f.toString()) is that you are printing an array, not a String. Java's array classes do not override the toString() method. Therefore the toString() method that is being called is the one from java.lang.Object which is defined to output the object's class name and its identity hashcode. (In this case, the class name of the byte[] class will be "[b".)

I think your confusion arises from the fact that you are mentally equating a String and a byte array. There are two reasons why this is conceptually wrong:

  • In Java, Strings are not arrays of anything. The String class a fully encapsulated class that cannot be cast to anything else .... apart from Object.

  • In Java, a String models a sequence of characters, not a sequence of bytes.

The latter is a key difference because there are many possible conversions between character sequences and bytes, many of which are lossy in one or both directions. When you call "hello".getBytes() you get the conversion implied by your platform's default character encoding, but you could have supplied a parameter to getBytes to use a different encoding in the conversion.


as f is not a string, toString() method of object class is called and not of String class. toString of String class returns a String and toString of object class returns :

getClass().getName() + '@' + Integer.toHexString(hashCode()) ..... aww aww dont go too far ...its same as : classname.@hexadecimal code for the hash code


You're not able to convert between a byte array and a String without providing an encoding method.

Try System.out.println(new String(f, "UTF8"));

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜