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 [[email protected]

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




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.