How to convert byte array to string in Scala?

Scala | Converting byte array to string: Here, we are going to learn how to convert byte array to string in Scala, its method with examples, and syntaxes?
Submitted by Shivang Yadav, on May 21, 2020

Byte Array in Scala is an array of elements of a byte type. String in Scala is a collection of the character data type.

Scala – Byte Array to String Conversion

For converting a byte array to string in Scala, we have two methods,

  1. Using new keyword
  2. Using mkString method

1) Converting byte array to string using new keyword

In this method, we will convert the byte array to a string by creating a string using the new String() and passing the byte array to the method.

Syntax

    val string = new String(byte_array)

Scala code to convert byte array to string using new keyword

// 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

Scala code 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.

Scala String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.