Reputation: 3
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
Upvotes: 0
Views: 83
Reputation: 11
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
Upvotes: 0
Reputation: 438
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.
Upvotes: 1