1

I am using implicit String constructor that handle byte array..but it results weird. Do I have to do something more for proper output..? Any help will be appreciated. Here is my code..

    byte[] arr = { 23, 34, 20, 65, 88, 95 };

    String s1 = new String(arr);
    System.out.println("First: "+s1);

    String s2 = new String(arr, 1, 3);
    System.out.println("Second: "+s2);

it prints:

First: ?"?AX_

Second: ?AX

Community
  • 1
  • 1
Hello World
  • 944
  • 2
  • 15
  • 39

2 Answers2

2

The String() constructor you are using is interpreting the bytes in the array according to the default character set for your Java environment. That can differ.

If you have a specific character encoding that you want to use, like "US-ASCII" or "UTF-8", then you should specify the character set using a different constructor, such as: String(byte[] bytes, String charsetName).

cybersam
  • 63,203
  • 6
  • 53
  • 76
1

This is correct. Those are the characters for the codes that you provided. If you change your byte array to this, you'll see characters a-f:

byte[] arr = { 97, 98, 99, 100, 101, 102 };
Edwin Torres
  • 2,774
  • 1
  • 13
  • 15