Asserting

Welcome back! Today's lesson is our last on imperative programming. Next time we'll be talking objects.

But, before we get there we still have a few exciting new concepts to discuss. We'll introduce two new pieces of syntax: continue and switch. Neither is particularly common, but they are good to know.

Next, we'll discuss software testing. Specifically, we'll learn how to use assert statements to help test our assumptions about our code as we go. You can use these to help you on the homework problem, include today's!

continue and switch

Before we wrap up our unit on imperative programming, there are a few bits of relevant Java syntax that we have yet to explore. Both of these are variants on what we've already learned, so learning them is a good way to review. Neither is particularly common, but you'll encounter them from time to time.

continue

Remember how we had a way to break out of a loop?

Well, we also have another loop-control keyword, named continue. Let's explore what it does, and what we might want to do with it:

switch

Remember if statements? They can get unwieldly! For example:

Particularly for long if statements with repetitive conditions, there's a better way, the switch statement. Let's look at how it works:

switch Expressions

Speaking of new Java features, recent version of Java include an new feature called switch expressions. You won't be tested on this, but it's super fun stuff. Let's explore:

assert

Hopefully by now you'll have noticed that writing correct code is hard. There are a lot of ways to make mistakes. So programmers are always on the lookout for ways to make their lives easier and attempt to avoid bugs before they happen.

One way to do this is to use another feature of Java known as assert statements. Let's look at how they work:

One important caveat: assert statements are not always turned on when you code is run. Typically they are enabled during development (when the programmers are running the code) and disabled in production (when actual users are running the code). But don't worry: assert is enabled on all of our playgrounds and for all of our homework problems.

Next, let's look at how we can use assert to help us on today's homework problem!

What's Next

Hey, you made it! The first chapter of CS 125 is almost in the books. (There are weekend homework problems.) But at this point you know all of the basic programming building blocks!

So what do we do now? Next time we'll begin talking about Java objects, which represent both a data structure and conceptual step forward.

Reflections / Projections

Reflections / Projections is a student-run tech conference held at Illinois every year. It's coming up! Check it out:

Rock On

I take requests! A student suggested that this song by Brothers Osborne was relevant for CS, since it's only by making lots of mistakes that we eventually get things right. I agree!