Home »
Scala »
Scala Programs
How to convert a string to byte array in Scala?
Scala | Converting string to byte array: Here, we are going to learn how to convert a given string to byte array in Scala programming language?
Submitted by Shivang Yadav, on May 21, 2020 [Last updated : March 10, 2023]
String in Scala is a sequence of characters. And, Byte Array in Scala is an array that stores a collection of binary data.
Scala – String to Byte Array Conversion
We can convert a string to byte array in Scala using getBytes() method.
Syntax
string.getBytes()
This will return a byte array.
Example 1: Scala code to convert string to byte Array
// Program to convert string to Byte Array
object MyClass {
def main(args: Array[String]) {
val string : String = "IncludeHelp"
println("String : " + string)
// Converting String to byte Array
// using getBytes method
val byteArray = string.getBytes
println("Byte Array :" + byteArray)
}
}
Output
String : IncludeHelp
Byte Array :[B@fac80
Explanation
In the above code, we have used the getBytes method to convert the string to byte array and then printed the byteArray using the println() method which gives the pointer value.
Example 2: Scala code to convert string to byte Array
// Program to convert string to Byte Array
object MyClass {
def main(args: Array[String]) {
val string : String = "IncludeHelp"
println("String : " + string)
// Converting String to byte Array
// using getBytes method
val byteArray = string.getBytes
// printing each value of the byte Array
println("Byte Array : ")
for(i <- 0 to byteArray.length-1)
print(byteArray(i) + " ")
}
}
Output
String : IncludeHelp
Byte Array :
73 110 99 108 117 100 101 72 101 108 112
Explanation
In the above code, we have created a String named string with value "IncludeHelp" and then used the getBytes to convert it into a byte Array then printed the elements of the array using for loop.
Scala String Programs »