KotlinJava

# Arrays

var values = intArrayOf(1, 2, 4)
print("CS ")
print(values[0])
print(values[1])
print(values[2])
print(" rocks!\n")
println("CS \${values[0]}\${values[1]}\${values[2]} rocks!")

In this lesson we’re going to learn some exciting new things, and also start to leverage what we already know to build our first small useful programs.

## Sequential DataSequential Data

Until now we’ve been limited to working with single data values. That’s all that our variables could store!

But a lot of data around us can’t be reduced to a single data value. So throughout our journey we’ll periodically upgrade our ability to work with data in our programs, allowing us to program more of the real world around us.

Our first step is to consider series: 0 or more values of the same type arranged in some order. For example, consider the three individual values 1, 2, and 4. I can consider them unordered as three separate values. Or, I can order them, in several different ways:

• 1, 2, 4
• 1, 4, 2
• 2, 1, 4
• 2, 4, 1
• 4, 2, 1
• 4, 1, 2

Notice that from 3 different values I can create 6 different unique orderings. And the order matters! If you were choosing an introductory CS course, you’d prefer 1, 2, 4 to 4, 2, 1. (Not like there is anything wrong with CS 421. It’s just not an introductory course.)

### Data StructuresData Structures

Putting multiple values in order is our first example of a data structure. Data structures bring structure to data. Putting values in a sequence is just one way that we can structure them. We’ll explore others later in the course.

Note also that the structure introduces additional data about the data that it stores. We sometimes calls this metadata, since it’s data about data! In the case of a sequence, the metadata is the position of each value in the series. Placing the values 1, 2, and 5 in the order 5, 2, 1, associates a position with each value: 5 is first, 2 is second, 1 is third.

## Kotlin ArraysKotlin Arrays

In Kotlin one of the ways that we can store sequential data is using an array. An array orders zero or more values. Let’s dive into to declaring and initializing our first array and then unpack what is happening slowly.

var values = IntArray(8)

This is not that different than what we’ve seen before. We see an assignment operator, meaning that there is a variable on the left and what is being assigned to it on the right. On the left we see something familiar: `var`, meaning the value can change, and `values` the name of the variable we are declaring and initializing.

The right side is a bit more mysterious: `IntArray(8)`. `Int` is the type, `Array` means we are creating an array, and the value `8` which appears inside square brackets sets the size. To create an array of four `Double`s we would use `DoubleArray(4)`, and similarly for the other Kotlin basic types.

In Kotlin, we cannot change the size of an array after it has been created. Later in the semester we’ll look at other sequential data structures that are more flexible. But, they are also built on top of arrays, so you’ll be able to understand exactly how they work.

We’re also going to see something a bit strange if we try and print values:

var values = IntArray(8)
println(values)

We’ll show you how to display the values stored inside Kotlin arrays in just a minute. But just be prepared for this confusing display if you try and directly print the value of a variable that stores an array.

### Array IndexingArray Indexing

We’ve created our first array! But how do we actually store and retrieve the data inside it? Let’s go over that together:

var temperatures = DoubleArray(12)
println(temperatures[0])
temperatures[0] = 78.8
println(temperatures[0])

Arrays put values in order. So, to access the data inside them we need to tell Kotlin what position to either save or retrieve. Here’s an example of changing the first value of an array:

var results = BooleanArray(4)
println(results[0])
results[0] = true
println(results[0])

Here’s an example changing the second value:

var results = BooleanArray(4)
println(results[1])
results[1] = true
println(results[1])

And the last (or fourth) value:

var results = BooleanArray(4)
println(results[3])
results[3] = true
println(results[3])

Notice something strange? Array indices start at 0. To a computer scientist, 0 means first, 1 means second, and 3 means fourth. This may seem strange to you when you are getting started, but it quickly becomes second nature:

var measurements = LongArray(8)

### Out of BoundsOut of Bounds

What happens if we use a bad position value? Let’s find out!

var letters = CharArray(4)
letters[-1] = 'X' // X marks the spot!

### Array InitializersArray Initializers

Just like we could set a variable with an initial value, we can do the same thing with arrays using array initializers. Let’s see how.

var letters = charArrayOf('C', 'S', '1', '9', '9')
println(letters[0])
println(letters[4])

You’ll notice above that when we initialize an array this way we don’t need to specify a size. Kotlin sets the size of the array based on the number of values passed to the initializer.

### Default ValuesDefault Values

Finally, you may wonder what values Kotlin uses to fill the empty arrays we have been creating. Use the playground below to find out!

var defaults = IntArray(4)
println(defaults[0])

### Sources of ConfusionSources of Confusion

Let’s walk through some of the possible bits of confusion regarding arrays.

var values = IntArray(4)

### Array TypesArray Types

In the examples above we’ve been relying on Kotlin’s type inference to set the types of our array variables properly. For example, in this example:

var values = IntArray(4)

Kotlin will infer that the type of `values` is an array of `Int`s, and enforce that throughout the rest of the program:

var values = IntArray(4)
values = CharArray(4) // Can't do this!

But how would we write out the type of an array? Let’s see!

var first = 4 // Inferred to be an Int
var second: Int = 4 // Type specified explicitly
var firstArray = IntArray(4) // Inferred to be Array<Int>
var secondArray: IntArray = IntArray(4) // Type specified explicitly

So the type for an array of `Int`s is `IntArray`, and for an array of `Boolean`s is `BooleanArray`—just the same as the way that we initialize an empty array!

## Digital JoysDigital Joys

We’re just getting started working with data. But even being able to work with series of data using arrays opens up some exciting possibilities. This is largely due to digitization: the conversion of data to numeric format so that computers can work with it. Let’s look at examples of digitization that produce sequential or linear data.

### A Note on Today’s HomeworkA Note on Today’s Homework

Note that today’s homework does not yet cover arrays. We’ll get there! But for now we’ll continue reinforcing other ideas we’ve learned recently.

## CS People: Grace HopperCS People: Grace Hopper

Grace Hopper made multiple pioneering contributions to computer science. Among other accomplishments, she helped invent COBOL, one of the first high-level programming languages. (And which is still in use today.) She also served in the Navy until almost 80 years of age, and retired as one of a small number of female admirals.