CodeBlanks Logo Icon CodeBlanks

length and methods

Learn .length and String methods.

length and methods

You find how many characters a String has with the .length property: "Welcome".length evaluates to 7. .length is a property, not a method; no parentheses needed.

To upper-case the letters you use .toUpperCase(), to lower-case them .toLowerCase(). For example "book".toUpperCase() returns "BOOK". These methods do not change the original string; they return a new one.

Methods return a new string

Important: .toUpperCase() and .toLowerCase() do not modify the original string. String name = "Alex"; name.toUpperCase(); produces a new string "ALEX" but name stays "Alex".

To keep the result you assign it to a new variable: String big = name.toUpperCase();. Now big is "ALEX" and name is "Alex". Strings in Dart are immutable; every method call creates a new string.

Practice Upper-case the city

Declare a String variable city with the value "Paris". Declare a new variable big and assign the result of city.toUpperCase() to it. Then print big with print(big);. The output on a single line must be PARIS.

Starter code

main.dart
// Declare city, build big with toUpperCase and print it

Sample solution

main.dart
String city = "Paris";
var big = city.toUpperCase();
print(big);

Expected output

PARIS

Questions and answers

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

1 Write the length call

Question
String word = "Welcome";
print(word____);
Answer
String word = "Welcome";
print(word.length);

Explanation: .length gives the character count of the String.

2 What does "book".toUpperCase() return?

main.dart
"book".toUpperCase()
  • "book"
  • "Book"
  • "BOOK" Correct answer
  • true

Explanation: toUpperCase upper-cases all letters: BOOK.

3 Match each method to its job

Term Meaning
.length Character count
.toUpperCase() Upper-cases letters
.toLowerCase() Lower-cases letters
print(x) Prints to screen

All lessons in Beginner