Kotlin
Java

Algorithms and Strings
Java

Created By: Geoffrey Challen
/ Updated: 2021-08-30

Today's lesson is a lot of fun. We'll integrate what we've learned recently about Strings, algortihms, and then functions. And then we'll get some practice approaching a few new problems using Strings.

Odds and Ends

But first, we have a few new things to cover.

Casting

When we started working with variables and Java's eight primitive types, we observed that there were certain types of assignments that would fail. For example:

But, there are also other kinds of assignments from one type to another that will succeed:

Let's discuss why that is, and how to can force Java to perform certain type changes when necessary.

Discuss type casting, both manual and automatic.

Strings Are Immutable

One of the important things to understand about Java's Strings is that none of the methods that we can call on them change that String. Instead, they always return a new String that may be modified in some way. Let's see that in action:

Demonstrate how String operations don't change their contents.

String Algorithms

Now let's have some fun and write a few new algorithms that work on Strings!

String Character Search

First, let's try and write a function that determines if a String contains a particular character. We'll sketch our our algorithm first, explore some potentially useful String methods, and construct and test a solution.

Show how to write a function that searches a String for a character. Sketch in comments first and then replace with code.

Structured String Parsing

Frequently when computers work with text data, we are processing data that was itself created by a machine. Or set up for machines to easily process.

One example is data stored in comma-separated-value format. Let's say we wanted to track how many people were tested for some random respiratory illness each day. We might save that data in a String that looked like this:

(Note that this is not real data!)

Let's experiment with how we might work with this kind of data. We'll use some existing String methods and a few new ones. We'll also use another unfamiliar method: Integer.parseInt, which allows us to convert a String to an int.

Walk through some examples using the CSV data. Use the same approach as previously: sketch in comments, then replace with code. First, parse it. Discuss Integer.parseInt. Then do something fun with data: total number of tests, or day with the most tests, or whatever.

Show how to complete the homework problem above. Feel free to cover multiple approaches!

Solution Walkthrough

Show how to complete the homework problem above. Feel free to cover multiple approaches!

Solution Walkthrough