← Back to Scala Course | Chapter 2: Variables & Types | Lesson 5 of 8

String

A String is a piece of text, like a word or sentence on a ribbon. Once made it cannot be edited in place, so changes produce a new string.

In this page:

  1. String
Syntax
scala
val text: String = "some text"
text.length
text.toUpperCase

String

A String is an immutable sequence of characters, written with double quotes. Strings support concatenation with +, a rich set of built-in methods, and interpolation with s"..." (covered in its own tutorial).

Because strings are immutable, every "modification" actually creates a new string.

Note: Prefer string interpolation (s"Hello $name") over + concatenation for readability.

Example: String

markup
object Main extends App {
  val first = "Ada"
  val last = "Lovelace"
  val full = first + " " + last

  println(full)
  println(full.length)
  println(full.toUpperCase)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trying to change a string in place like s(0) = X, when strings are immutable and you must create a new one.
  2. Comparing strings with eq and expecting content comparison, when == compares the content.
  3. Forgetting that full.length takes no parentheses in the code, and writing full.length() where the style differs; both work but Scala convention omits them.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.