Scala String getBytes() Method with Example

Here, we will learn about the getBytes() method of string class in Scala. It is used to convert the string to a byte array. We will see its working, syntax and example.
Submitted by Shivang Yadav, on February 03, 2021

String is an immutable collection that stores sequences of characters.

String getBytes() Method

The getBytes() method on strings is used to convert the given string into an array of bytes. It used the default character set of the platform you are working on for the byte conversion.

Syntax:

string_Name.getBytes()

Parameters: The method is a parameter-less method i.e. it does not accept any parameter.

Return Value: It returns a byte array.

Example 1:

object myObject {
    def main(args: Array[String]) {
        val string1 = "scala"
        val byteArr = string1.getBytes()
    
        println("The pointer to the byte array is " + byteArr)
    }
}

Output:

The pointer to the byte array is [B@50b8ae8d

Example 2:

object myObject {
    def main(args: Array[String]) {
        val string1 = "scala"
        val byteArr = string1.getBytes()
    
        println("The bytes converted from the string are ")
        for(i <- 0 to byteArr.length-1 )
            print(byteArr(i) + " ")
    }
}

Output:

The bytes converted from the string are 
115 99 97 108 97 

Here, as you can see that the elements of the byte array are the ascii values of the character of the string. So, it converts each character into its equivalent byte value and then stores them in a byte array.



Comments and Discussions!

Load comments ↻





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