How to convert byte array to string in Java

3 Answers

0 votes
import java.nio.charset.StandardCharsets;

public class MyClass {
    public static void main(String args[]) {
        byte[] bytes = "java".getBytes();
        
        String s = new String(bytes, StandardCharsets.UTF_8);
        
        System.out.println(s);
    }
}
 
 
 
/*
run:
 
java
 
*/

 



answered Mar 22, 2021 by avibootz
0 votes
import java.nio.charset.StandardCharsets;

public class MyClass {
    public static void main(String args[]) {
        byte[] bytes = {0x4A, 0x61, 0x76, 0x61};  

        String str = new String(bytes, StandardCharsets.US_ASCII);
        
        System.out.println(str);
    }
}
 
 
 
 
/*
run:

Java

*/

 



answered Oct 25, 2023 by avibootz
0 votes
import java.nio.charset.Charset;

public class MyClass {
    public static void main(String args[]) {
        byte[] bytes = {0x4A, 0x61, 0x76, 0x61};  
        
        Charset utf8 = Charset.forName("UTF-8");

        String str = new String(bytes, utf8);
 
        System.out.println(str);
    }
}
  
  
  
  
/*
run:
 
Java
 
*/

 



answered Oct 26, 2023 by avibootz

Related questions

4 answers 211 views
2 answers 190 views
2 answers 391 views
2 answers 239 views
1 answer 213 views
1 answer 226 views
...