0

I am a beginner in java I want to convert String to a byte array and vice versa. when I compare the result input_bytes with output.getBytes(). I found that they are not compatible. this is my code.

    String input = "bg@%@bg0";
    byte[] input_bytes = input.getBytes();
    String output = new String(input_bytes);
    System.out.println(input_bytes);
    System.out.println(output.getBytes());

the result :

[B@15db9742
[B@6d06d69c

How can I get the same byte array from input and output? and what is the problem in my code?

  • Does this answer your question? [Convert a String to a byte array and then back to the original String](https://stackoverflow.com/questions/7947871/convert-a-string-to-a-byte-array-and-then-back-to-the-original-string) – pczeus Apr 26 '20 at 21:12

1 Answers1

4

Try:

System.out.println(Arrays.toString(input_bytes));

You need to use Arrays.toString() method.

Output: [98, 103, 64, 37, 64, 98, 103, 48]

Note: Here Arrays.toString(byte[]) returns a string representation of the contents of the specified byte array.

Nitin Bisht
  • 5,053
  • 4
  • 14
  • 26