0

I have a problem about byte array convert to String as below code:

public static void main(String[] args) {

        System.out.println("--->" + new String(new byte[5]) + "<---");
}

In windows os result:

--->    <---

In mac os result:

--->��������������������<---

Why? Does everybody has the problem? Help...

3
  • 1
    What is it you are actually expecting? Why building a String with a byte array that is not initialized? Commented Sep 1, 2015 at 7:47
  • Because the business requirement, we have to allocate the 20 bytes array first. Commented Sep 2, 2015 at 11:58
  • I cannot believe the business requirement is to print an uninitialized byte array. Commented Sep 2, 2015 at 12:15

2 Answers 2

7

You are using a byte array which is full of \0 nul bytes.

How this is translated into a character depends on the character encoding you are using. In your case, you haven't specified the character encoding so it is what ever is the default on your OS, which you can expect will be different on different OSes.

The simple answers is, don't leave this to chance and specify the character encoding you want.

 System.out.println("--->" + new String(new byte[5], "UTF-8") + "<---");

Note: you have another issue that the fonts will be different on different machines, but you can't control the console font from within a Java program.

Sign up to request clarification or add additional context in comments.

Comments

2

When you create a String from a byte array, the byte values (0-255) are converted into UTF-16 characters (see the javadoc of java.lang.String). How this conversion is done depends on how the byte values are interpreted. For example: Multiple bytes can make up a single character in the String. If you don't specify the character encoding to use, the default encoding is used. This can differ between platforms. See this Oracle tutorial about byte encodings and Strings.

To create a String using UTF-8 (a common choice for Java applications), you can do this:

byte[] bytes = new byte[5];
// TODO: fill array with values
String utf8 = new String(bytes, java.nio.charset.StandardCharsets.UTF_8);

(using java.nio.charset.StandardCharsets which is available since Java 7)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.