KotlinCS 124 LogoJava
PrevIndexNext
Kotlin
Java
  • Implementing a Map : 04/26/2024

  • map-reduce-filter : 04/25/2024

  • Generics : 04/24/2024

  • Hashing : 04/23/2024

  • Binary Search : 04/22/2024

  • MP3: Course Ratings : 04/19/2024

  • Quicksort : 04/18/2024

  • Merge Sort : 04/17/2024

  • Sorting Algorithms : 04/16/2024

  • MP Debugging Part 1 : 04/15/2024

  • MP2: Course Activity : 04/12/2024

  • Practice with Recursion : 04/11/2024

  • MP Debugging Part 0 : 04/10/2024

  • MP2: API Client : 04/09/2024

  • MP2: API Server : 04/08/2024

  • Trees and Recursion : 04/05/2024

  • Trees : 04/04/2024

  • Recursion : 04/03/2024

  • MP1: Filtering and Search : 04/02/2024

  • MP1: Loading and Sorting : 04/01/2024

  • Lists Review and Performance : 03/29/2024

  • Linked Lists : 03/28/2024

  • Algorithms and Lists : 03/27/2024

  • Continuing MP0 : 03/26/2024

  • Getting Started with MP0 : 03/25/2024

  • Lambda Expressions : 03/22/2024

  • Anonymous Classes : 03/21/2024

  • Practice with Interfaces : 03/20/2024

  • Implementing Interfaces : 03/19/2024

  • Using Interfaces : 03/18/2024

  • Working with Exceptions : 03/08/2024

  • Throwing Exceptions : 03/07/2024

  • Catching Exceptions : 03/06/2024

  • References and Polymorphism : 03/05/2024

  • References : 03/04/2024

  • Data Modeling 2 : 03/01/2024

  • Equality and Object Copying : 02/29/2024

  • Polymorphism : 02/28/2024

  • Inheritance : 02/27/2024

  • Data Modeling 1 : 02/26/2024

  • Companion Objects : 02/23/2024

  • Encapsulation : 02/22/2024

  • Constructors : 02/21/2024

  • Objects, Continued : 02/20/2024

  • Introduction to Objects : 02/19/2024

  • Compilation and Immutability : 02/16/2024

  • Practice with Collections : 02/15/2024

  • Maps and Sets : 02/14/2024

  • Lists and Type Parameters : 02/13/2024

  • Imports and Libraries : 02/12/2024

  • Multidimensional Arrays : 02/09/2024

  • Practice with Strings : 02/08/2024

  • null : 02/07/2024

  • Algorithms and Strings : 02/06/2024

  • Strings : 02/05/2024

  • Functions and Algorithms : 02/02/2024

  • Practice with Functions : 02/01/2024

  • More About Functions : 01/31/2024

  • Errors and Debugging : 01/30/2024

  • Functions : 01/29/2024

  • Practice with Loops and Algorithms : 01/26/2024

  • Algorithms : 01/25/2024

  • Loops : 01/24/2024

  • Arrays : 01/23/2024

  • Compound Conditionals : 01/22/2024

  • Conditional Expressions and Statements : 01/19/2024

  • Operations on Variables : 01/18/2024

  • Variables and Types : 01/17/2024

  • Welcome to CS 124 : 01/16/2024

Strings

var greeting = "Hello, world!"
println(greeting)
println(greeting.length)
var parts = greeting.split(" ")
println(parts[0])

Let’s take two big steps forward in our journey in computer science. First, we’ll learn how to work with text data in Kotlin, using a data type called a String. Strings also represent another step forward, since they are the first type that we will work with as a Kotlin object. We’ll spend a lot of time discussing objects in future lessons, so this is our first taste of what is yet to come.

Working with Text
Working with Text

Language is one of the things that makes humans special. And, while many animals communicate through vocalizations, written language is even more unique to our species. Words and text have long played an incredibly important role in human societies. So clearly this is a kind of data that we want to be able to work with in our computer programs.

Happily, Kotlin has a special data type specifically for working with text:

var welcome = "Hello, world!"
println(welcome)

Note how Strings differ from chars, in that they are enclosed in double quotes (”) rather than single quotes (’):

var remember = "You are not alone" // Double quotes
var first = 'U' // Single quotes
var fancy = "And if you need a \", we precede it with a backslash."
var also = """You can also use triple quotes, making including "s easy!
And even new lines!"""
println(remember)
println(fancy)
println(also)

Like Kotlin Chars, Kotlin Strings can store characters outside of the basic ASCII character set:

// I translated this automatically, so it may say something stupid.
// If you know how to translate this correctly, get in touch!
var remember = ""
println(remember)
// Or, less formally...
remember = ""
println(remember)
// (Thanks for the help with the translation above...)

A full discussion of Unicode and how characters are represented in modern programming languages is outside the scope of this class. But it’s a fascinating story with lots of interesting wrinkles. Safe to say, we have fully overcome the limitations of early programs ability to work with non-latin alphabets. Unicode even includes emoji:

(Note that the in-browser editor gets a bit weird around emoji, probably because they aren’t the same width as other characters.)

var remember = "➡️👤 are ❌️ alone"
println(remember)

Concatenation
Concatenation

One useful thing that we can do with Strings is combine them. Kotlin allows us to do this using the + operator:

var first = "Xyz"
var last = "Challen"
println(first + " " + last + " is a cat")
var fullName = first + " " + last
println(first + " " + last + " is not a dog")

Interpolation
Interpolation

However, in Kotlin it is usually more convenient to use String interpolation. We’ve already seen this in action in our println examples:

var first = "Xyz"
var last = "Challen"
println("$first $last is a cat")
var fullName = "$first $last"
println("$fullName is not a dog")

String interpolation allows us to create new Strings that include the values of variables, which are prefixed by a $, as shown above. This is quite convenient, and we’ll prefer it to String concatenation. (It is also more powerful in ways that we haven’t explored quite yet!)

println v. print
println v. print

As a final note, let’s examine the difference between println and print:

println("Hello, world!")

Practice: Reformat a Phone Number

Created By: Geoffrey Challen
/ Version: 2020.9.0

Let's get some practice working with Kotlin Strings: an incredibly useful data type for working with text.

Write a function called reformatPhoneNumber. It should take a String containing a phone number in the format 111-222-3333 and return it reformatted as (111) 222-3333.

You will want to explore the various String methods to help you with this task. In particular, you may find split and substring helpful. There are solutions that use split, others that use substring, and probably others that use neither!

Strings as Objects
Strings as Objects

On one hand, Strings just seem like any other Kotlin variable. But there is something new going on here. Let’s explore together:

var example = "I'm an example"

Strings are Objects
Strings are Objects

The unusual behavior that we observed above is due to the fact that String is not one of the eight basic Kotlin types. In fact everything in Kotlin—including the basic types—is an object! Even the basic types have methods that we can call:

var first = 1
println(first.inc())
// We can even call this method directly on a literal!
println(2.inc())

We’ll be talking a lot about objects in future lessons, but for now we’ll define an object as something that combines state and behavior, or data and functionality. Kotlin objects can be seen as uniting two of the basic building blocks that we’ve already been exploring: variables and methods. Like a variable, Kotlin objects store information. Strings store a series of characters. But in addition, Kotlin objects also come with built-in methods that we can call! Frequently, those methods operate on the data contained in the object.

Let’s look at how that works out with Strings, our first object. Note that this is a screencast, rather than a walkthrough, so that we can consult some documentation together!

The best way to familiarize yourself with these features is to browse the official String documentation. Over the set of homework problems on Strings that start with this lesson, we may expect you to use some of their built-in features, and point you at the relevant documentation.

Dot Notation
Dot Notation

To call a method on a String, we use so-called dot notation. Let’s explore that in the following walkthrough:

var name = "Chuchu Challen"

Practice: Email to NetID

Created By: Geoffrey Challen
/ Version: 2021.8.0

Write a function called emailToNetID. It should take a String containing an @illinois.edu email like hello@illinois.edu and return the NetID, which in this case would be "hello", as a String. You can assume that the passed String will contain a single @ character. And you should require that the passed String ends with @illinois.edu.

You will want to explore the various String methods to help you with this task, particularly split.

Homework: String to Latitude

Created By: Geoffrey Challen
/ Version: 2022.8.0

It's common when working with data to have to convert it from one format to another. Frequently we find data as text and need to extract it to other formats so that we can work with it in our programs.

As an example, consider the (very special) position "40.10986682, -88.22831928", represented as a string containing latitude and longitude values separated by a comma with latitude first. Write a method stringToLatitude that takes a String in the format above as input and returns the latitude that it contains as a Double. So for the string above you would return the Double 40.10986682.

The two values will always be separated by a comma, but there may be a variable amount of whitespace surrounding each value—which is common in data that was entered by hand.

You should explore String methods that may help you, including split and trim. Once you have a String containing a double value, you can convert it to the double type using string.toDouble().

More Practice

Need more practice? Head over to the practice page.