Scala – String

Scala string is a sequence of characters inside quotes. It is an immutable object like in java that means its values can not be modified. When you write a String in REPL (Read-Evaluate-Print-Loop) environment, and get the name of the String literal, it will print java.lang.String which tells us that scala uses java String class, hence allows us to use its methods in scala.

String in Scala prints java.lang.String

As you can see in the above image, we have defined the type as String while declaring variable str. What if we do not mention the type and write the String as given below?

It will also work , as compiler understands it as String literal and creates a string object str. We can see an example how it is an immutable object. If we replace the characters in the string , it gives a new string and original string str remains intact. We are replacing “Emp” with “123” ,and it gives a new string. But String str remains as Employee when printed again.

Now, let’s see some important methods of string.

Consider that we have a string object as – val str = “Employee”.


It returns the length of the string in characters.


It returns the part of string staring at index i. Index start from 0.


It returns the part of String starting at index i and goes till index (j-1).


It also works the same as substring and gives the same result.


It returns boolean value as true if x is substring of str.


It returns the index of first occurrence of substring in string str or -1 if not present.


Converts string into lower case.


Converts string into uppercase.


returns a string with first character as upper case.


returns boolean value true if string object is empty else false. It is same like str.length==0.


returns true if str starts with x. It is case sensitive.


returns true if str ends with x. It is case sensitive.


returns reversed string.


It returns a new string with all characters x replaced by y.


It returns a string with white spaces removed both the side.


It splits the string on the basis of delimiter and returns a array of strings.

Scala Closure
Scala - String Interpolation
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *