Byte Array in Scala is an array of elements of a byte type. String in Scala is a collection of the character data type.
Convert byte array to string
For converting a byte array to string in Scala, we have two methods,
- Using new keyword
- Using mkString method
Program to convert a byte array to string
Output:
Explanation:
In the above code, we have created a byte array named byteArray and converted it to a string by passing the byteArray while creating a string named convertedString using new String().
2) Converting byte array to String using mkString method
We can use the mkString method present in Scala to create a string from an array. But prior to conversion, we have to convert byte array to character array.
Syntax:
Program to convert byte array to String using mkString method
Output:
Explanation:
In the above code, we have used the mkString method to convert a byte array to string. We have created a byte Array named byteArray and then used the mkString method to convert it to a string. But before conversion, we have converted the byte to their character equivalent using .map(_.toChar) method. The result of this is stored to a string named convertedString which is then printed using println method.
need an explanation for this answer? contact us directly to get an explanation for this answer