0

I have converted a string into byte in java and stored that byte data into a string variable.

String s = "anu";
byte[] d = s.getBytes();
String e = Arrays.toString(d);

How can I convert that string (in this case variable 'e') again into the same string assigned to s i.e."anu";

MaxSteel
  • 373
  • 1
  • 3
  • 10

2 Answers2

4

Firstly, I'd strongly advise against using getBytes() without a charset parameter.

Next, just use the string constructor that takes a byte array and a charset:

String s = "anu";
byte[] d = s.getBytes(StandardCharsets.UTF_8);
String e = new String(d, StandardCharsets.UTF_8);

Note that you should only do this for data which is inherently text to start with. If you've actually started with arbitrary binary data (e.g. an image, or the result of compression or encryption) you should use base64 or hex to represent it in text, otherwise you're very likely to lose data.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
0

you can do directly this

String s1 = new String(d);
System.out.println(s1);

Or if you really want to have the "e" variable

String s2 = new String(e);
System.out.println(s2);