Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to initialize byte array in Java?

I have a byte array like this: (this is not the actual byte array, I have modified it)

[69, 121, 101, 45, 62, 118, 101, 114, 196, 195, 61, 101, 98]

I want to know how can I initialize this in Java so that I can convert this byte array to String? Below line doesn't work.

// this doesn't work
byte[] bytes = [69, 121, 101, 45, 62, 118, 101, 114, 196, 195, 61, 101, 98];

// now convert to string
String data = new String(bytes, StandardCharsets.UTF_8);
like image 677
user1950349 Avatar asked Dec 02 '22 14:12

user1950349


1 Answers

This should work

  byte[] bytes = {69, 121, 101, 45, 62, 118, 101, 114, (byte) 196, (byte) 195, 61, 101, 98};

Byte can hold upto -128 to 127 only. Some of the values are exceeding the limit of a byte value. So you need to cast them to byte.

like image 85
Suresh Atta Avatar answered Dec 11 '22 12:12

Suresh Atta