CodeBlanks Logo Icon CodeBlanks

Creating strings

Learn to create Strings with single and double quotes.

Creating strings

In Dart text is held in the String type. You write a String with single quotes ('hello') or double quotes ("hello"). Both give the same result; the choice is yours.

To assign a String to a variable you use the String type or the var keyword: String name = "Alex"; or var name = "Alex";. To print the value to the screen a print(name); call is enough.

Single and double quotes

In Dart single and double quotes are equivalent; which one you choose depends on which quote type appears inside the string. For example "Alex's" is more readable than 'Alex\'s'.

Many Dart programmers prefer double quotes because single quotes (apostrophes) appear more often inside text. What matters is consistency: avoid mixing the two in the same file.

Practice Print the String variable

Declare a String variable name with the value "Alex". Then print it to the screen with print(name);. The output on a single line must be Alex.

Starter code

main.dart
// Declare the String variable and print it

Sample solution

main.dart
String name = "Alex";
print(name);

Expected output

Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which one is a valid String literal?

main.dart
?
  • "hello" Correct answer
  • <hello>
  • [hello]
  • {hello}

Explanation: Text in double quotes is a String.

2 Complete the String declaration

Question
String name = ____;
print(name);
Answer
String name = "Alex";
print(name);

Explanation: "Alex" is a double-quoted String literal.

3 Match the quote type to the example

Term Meaning
"hello" Double-quoted
'hello' Single-quoted
"Alex's" Contains single quote
'"Yes"' Contains double quote

All lessons in Beginner