Q:

How to convert byte array to string in Scala?

belongs to collection: Scala String Programs

0

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,

  1. Using new keyword
  2. Using mkString method

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to convert a byte array to string

// Program to convert Byte Array to String
object MyObject {
    def main(args: Array[String]) {
        val byteArray = Array[Byte](73, 110, 99, 108, 117, 100, 101, 104, 101, 108, 112)
        val convertedString = new String(byteArray) 
        println("The converted string '" + convertedString + "'")
    }
}

Output:

The converted string 'Includehelp'

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:

    (byteArray.map(_.toChar)).mkString

Program to convert byte array to String using mkString method

// Program to convert Byte Array to String
object MyObject {
    def main(args: Array[String]) {
        val byteArray = Array[Byte](73, 110, 99, 108, 117, 100, 101, 104, 101, 108, 112)
        val convertedString = byteArray.map(_.toChar).mkString
        println("The converted string '" + convertedString + "'")
    }
}

Output:

The converted string 'Includehelp'

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

total answers (1)

Scala String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to convert a string to date in Scala?... >>
<< How to convert a string to byte array in Scala?...