What is byte data type?
It’s an 8-bit signed two’s complement integer, capable of storing values from -128 to 127. Bytes are used for low-level data storage and handling, often dealing with raw binary data or small numerical values. byte occupies 8 bits (1 byte) of memory space. It’s more memory-efficient and suitable for storing smaller-sized numerical or binary data.
byte array is primarily utilized for numerical data manipulation and low-level bit operations. It’s commonly employed in File I/O operations, image processing, file handling, network communication, and situations where raw binary data needs to be managed efficiently.
Example of byte:
byte[] byteArray = new byte[1];
byteArray[0] = 10;
byteArray[1] = 20;
byteArray[4] = 50;
//geneate output: 10
System.out.println("byte array: " + byteArray[0]);
1. Convert byte[] to String:
byte[] bytes = "I am Byte".getBytes();
String str = new String(bytes, StandardCharsets.UTF_8); // Using UTF-8 encoding
//Prints I am Byte
System.out.println(str);
Caution: Specifying the correct character encoding is crucial to properly interpret the bytes into a readable string. Like we have specified: StandardCharsets.UTF_8.
Implications of not using Correct Charsets?
Encoding Issues:
If we Choose an incorrect encoding during conversion, then it can lead to data loss or incorrect interpretation of byte data. Let’s take couple of examples for this use case.
Example: Failure Case of Incorrect Encoding usage:
// UTF-8 encoded bytes byte[] utf8Bytes = "I am NON ASCII, 你好".getBytes(StandardCharsets.UTF_8); // Attempt conversion to ASCII String asciiString = new String(utf8Bytes, StandardCharsets.US_ASCII); // Output: Garbled text or data loss System.out.println("ASCII String: " + asciiString);
Example: Mismatch Encoding Issue (Failure Case)
// UTF-8 encoded bytes byte[] utf8Bytes = "This is UTF, 你好".getBytes(StandardCharsets.UTF_8); // Attempt conversion to ISO-8859-1 String isoString = new String(utf8Bytes, StandardCharsets.ISO_8859_1); // Output: Garbled text or data loss System.out.println("ISO-8859-1 String: " + isoString);
2. Convert String to byte[]
We can convert a String to a byte[] array using the getBytes() method provided by the String class.
String str = "I am String Data Type"; // Using UTF-8 encoding byte[] byteArray = str.getBytes(StandardCharsets.UTF_8);
Conclusion: Convert Byte[] to/from String
- We would use String constructor to convert byte to String in Java & getBytes method to perform reverse conversion.
- However, most important things is the usage to StandardCharsets enum. We need to be cautious and always specify the correct destination encoding. Otherwise, we would run into encoding issues.