×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala String getBytes() Method

By IncludeHelp Last updated : October 22, 2024

Description and Usage

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.