Home » Scala language

Strings in Scala

A string is a sequence of characters. In this Scala string tutorial, we will learn some basics of Scala strings and example code that elaborates Scala string usage in the real-world programming.
Submitted by Shivang Yadav, on July 03, 2019

Scala strings

A string is a sequence of characters. In Scala, the String object is immutable. This means that the strings in Scala cannot be modified in the program. Its value given at the time of creation will remain constant throughout the program.

You can think of the string as a sequence of characters i.e. an array of characters that are "0" indexed. This means the first character has index 0, the second character has index 1, and so on. Every single character from the string can be extracted by using its index number.

For example, suppose we have an array "arr" which defines some text, we can access any character by using its index number.

    def arr = "Include Help is awesome"
    arr(4)      // Output will be u
    arr(11)     // Output will be p
    arr(34)     // Output will give error array out of bond 
                // and a list of error related to that

All operations on the Scala string are defined in the String class. Which can be imported from "java.lang.String".

There are two syntaxes that can be used to define a string in Scala:

1) The object is created and a string is fed to it,

    var name = "Include Help"
    val name = "Include Help"  

2) The object of String type is created using specifier and then the string is fed to it,

    var name : Sting = "Include Help"
    val name : Sting = "Include Help"


object MyClass {
        // A program to show implementation of scala string 
      def main(args: Array[String]) {
         var name = "Include Help"
         println("Welcome" + name)
         println("the 5th character of you name is" + name(5));


WelcomeInclude Help
the 5th character of you name isd


In the above example, we have created a string named name and Fed to it the value "include help". Then we have printed the string using the println() function. Also, we have printed the fifth character of the string using the index selection method of printing character values of a string that we have discussed previously in this tutorial.

There are many functions defined over the string object in the string class and We will be going through them in the next tutorial.

Comments and Discussions!

Load comments ↻

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