×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala String hashCode() Method

By IncludeHelp Last updated : October 22, 2024

Description and Usage

The hashCode() method on strings is used to return the hash code for the given string in Scala.

Syntax

string_Name.hashCode()

Parameters

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

Return Value

It returns an integer which is the hash code for the given string in Scala.

Example 1

object myObject {
    def main(args: Array[String]) {
        val string1 = "scala"
        val hash = string1.hashCode()
    
        println("The hash code for the string is " + hash)
    }
}

Output:

The hash code for the string is 109250886

Example 2

object HashCodeExample {
  def main(args: Array[String]): Unit = {
    val str1 = "Hello, Scala!"
    val str2 = "Hello, World!"
    val str3 = "Hello, Scala!"

    // Compute hash codes
    val hash1 = str1.hashCode()
    val hash2 = str2.hashCode()
    val hash3 = str3.hashCode()

    // Print hash codes
    println(s"Hash code of '$str1' is: $hash1")
    println(s"Hash code of '$str2' is: $hash2")
    println(s"Hash code of '$str3' is: $hash3")

    // Checking equality of hash codes
    println(s"Does str1 have the same hash code as str3? ${hash1 == hash3}")
  }
}

Output:

Hash code of 'Hello, Scala!' is: 1763087995
Hash code of 'Hello, World!' is: 1794106052
Hash code of 'Hello, Scala!' is: 1763087995
Does str1 have the same hash code as str3? true

Comments and Discussions!

Load comments ↻





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