0

Taken from this site: https://www.journaldev.com/770/string-byte-array-java

package com.journaldev.util;

public class ByteArrayToString {

    public static void main(String[] args) {
        byte[] byteArray = { 'P', 'A', 'N', 'K', 'A', 'J' };
        byte[] byteArray1 = { 80, 65, 78, 75, 65, 74 };

        String str = new String(byteArray);
        String str1 = new String(byteArray1);

        System.out.println(str);
        System.out.println(str1);
    }
}

Why is the output:

PANKAJ

PANKAJ

I can't see how it isn't:

PANKAJ

806578756574

4
  • 1
    80 is not the same thing as "80". Commented May 11, 2018 at 20:50
  • The string constructor takes in an array of bytes and interprets them as characters. The byte 80 represents the character 'P', etc. Commented May 11, 2018 at 20:51
  • ASCII codes are used under the hood when you convert the byte array to string Commented May 11, 2018 at 20:51
  • I had an inkling that was the case. Thank you for helping me see how to identify it as such. Commented May 11, 2018 at 20:52

2 Answers 2

1

byte[] bytes constructor will parse the data contained, as @khelwood said it comments, the number are the ASCII representation of the letter so 80 represents a 'p' character.

if you want your output as you want, you should use

String[] srtArray = {"P","A"...}
String[] srtArray = {"80","65"...}

In the case of { 'P', 'A'...}, they are already encoded but number will be converted since they are stated as numbers and not string. "80" is not the same as 80.

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

Comments

0

Try this code:

public class ByteArrayToString {
  public static void main(String[] args) {
        byte[] byteArray = { 'P', 'A', 'N', 'K', 'A', 'J' };
        byte[] byteArray1 = { 80, 65, 78, 75, 65, 74 };

        String str = new String(byteArray);
        String str1 = new String(byteArray1);

        System.out.println(str);
        for (byte b : byteArray1) {
            System.out.print(b);
        }
        //System.out.println(str1);
    }

} Program output

1 Comment

Usually code only answers are discouraged. Instead, post an in-depth explanation alongside.

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.