Scala

17 / 51
   

Scala - Strings

A string is a sequence of one or more characters.
The String is an immutable object in Scala which means that its object can not be changed, only reference to the object can be changed.
In below example, when variable str is assigned a new value "hello all", String object doesn't change, rather a new String object is created in memory and reference to the new object is set to str.
Similarly, when string str is concatenated with another string " there", String object doesn't change and its value remains same which is "hello all".
But when string str is assigned the output of concatenation, a new String object is created in memory and reference to the new object is set to str.

object Hello {
   def main(args: Array[String]) {
      var str:String = "hello"
      println(str)
      str = "hello all"
      println(str)
      str.concat(" there")
      println(str)
      str = str.concat(" there")
      println(str)
   }
}