Java getBytes ()

Do you know the problem why I don't get Hello

byte f [] ="hello".getBytes(); System.out.println(f.toString()); 
+4
source share
5 answers

Because byte[]#toString() (usually) is not implemented as a new String(byteArray) , which will lead to the expected result (for example, System.out.println(new String(byteArray));

You can give this page an eye ...

+11
source

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

0
source

The reason you get the "weird" output from System.out.println(f.toString()) is because you are printing an array, not a string. Java array classes do not override the toString() method. Therefore, the toString() method that is called is the one from java.lang.Object that is defined to display the class name of the object and its hashcode identifier. (In this case, the class name of the byte[] class will be "[b".)

I think your confusion arises because you are mentally equating an array of String and byte. There are two reasons why this is conceptually wrong:

  • In Java, strings are not arrays. The String class is a fully encapsulated class that cannot be attributed to anything else ... except an object.

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

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

0
source

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

getClass().getName() + '@' + Integer.toHexString(hashCode()) ..... they all don't go too far ... just like: classname.@hexadecimal hash code

0
source

You cannot convert between an array of bytes and a String without providing an encoding method.

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

-2
source

Source: https://habr.com/ru/post/1306167/


All Articles