What a string is
A string is a piece of text: any sequence of characters you can type, including letters, digits, spaces and symbols. Programs use strings for names, messages and anything else that is words rather than numbers. In Scala the type is called String.
Writing a string
To write a string, put the text between double quotes:
println("My name is Andy")
println("Welcome to the course")
The output is:
My name is Andy
Welcome to the course
The quotes are not printed. They are not part of the string; their only job is to tell Scala where the text starts and where it ends. Everything between them, spaces included, is part of the string.
Double quotes only
Scala uses double quotes for strings. Single quotes mean something else: 'a' is a Char, a single character, and a single-quoted piece of text with several characters is an error. When you want a string, even a one-character one, use double quotes.
Strings versus numbers
The quotes change what a value is. 12 is a number you can do arithmetic with. "12" is two characters of text. With +, a number adds and a string joins:
println(12 + 1)
println("12" + 1)
13
121
In the second line the number is turned into text and attached to the end of the string. Subtraction is different: "12" - 1 doesn't compile, because a String has no - method.
Joining and measuring strings
The + operator joins two strings into a new one, and the length member tells you how many characters a string holds, spaces included:
println("Hello" + " " + "world")
println("Andy".length)
Hello world
4
A string can also be empty, written "". It has length 0 and prints as an empty line.
The most common mistake: a missing quote
Every string needs both of its quotes. This line is missing the closing one:
println("Welcome!)
Scala can't tell where the text ends, so it stops with the compile error unclosed string literal and the program does not run. The fix is to add the quote before the closing parenthesis:
println("Welcome!")
Matching pairs matter in general. Whenever you open a quote or a parenthesis, make sure there is something to close it.
Quotes inside a string
To put a double quote inside a string, write a backslash before it:
println("She said \"hi\"")
She said "hi"
The backslash tells Scala that this quote is part of the text and not the end of the string.
The exercise
The task is to print the text I love coding!. Put the text in double quotes and pass it to println:
println("I love coding!")
The console shows I love coding!, without the quotes. The text must match exactly, including the capital I and the exclamation mark at the end.
Key takeaways
- A string is text written between double quotes.
- The quotes mark the start and end of the string and are not printed.
12is a number and"12"is a string;+adds the first and joins the second.- A missing closing quote gives an
unclosed string literalerror.
