×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

Scala String intern() Method

By IncludeHelp Last updated : October 22, 2024

Description and Usage

The intern() method on strings is used to check canonical presentation of the given string. It returns the standard representation of the given string.

Syntax

string_Name.intern()

Parameters

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

Return Value

It returns a string which is a canonical presentation of the given string.

Example 1

object myObject {
    def main(args: Array[String]) {
        val string1 = "includehelp\t is a great place to learn programming. \n They have the best programming tutorials"
        val canonicalString = string1.intern()
    
        println("The standard string is \n'" + canonicalString + "'")
    }
}

Output

The standard string is 
'includehelp	 is a great place to learn programming. 
 They have the best programming tutorials'

Example 2

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

    // Check reference equality before interning
    println(s"Before interning: str1 == str2? ${str1 == str2}")  // true (content is equal)
    println(s"Before interning: str1 eq str2? ${str1 eq str2}")  // false (different references)
    println(s"Before interning: str1 eq str3? ${str1 eq str3}")  // false (different references)

    // Intern str1 and str2
    val internedStr1 = str1.intern()
    val internedStr2 = str2.intern()

    // Check reference equality after interning
    println(s"After interning: internedStr1 eq internedStr2? ${internedStr1 eq internedStr2}")  // true (same reference)
    println(s"After interning: internedStr1 eq str3? ${internedStr1 eq str3}")  // true (same reference)
  }
}

Output

Before interning: str1 == str2? true
Before interning: str1 eq str2? false
Before interning: str1 eq str3? false
After interning: internedStr1 eq internedStr2? true
After interning: internedStr1 eq str3? true

Comments and Discussions!

Load comments ↻





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