1. Why arrays are needed
When you’re just starting to program, it can feel like you can spawn variables endlessly: score1, score2, score3… and everything will be fine. But reality quickly reminds you: a programmer is not an accountant with a calculator, and storing a “list of similar things” in dozens of separate variables is a fast track to chaos, bugs, and misery.
Imagine a task: store steps for a week, or grades for 10 tests, or temperature by day. If you do it with separate variables, you immediately run into three problems: it’s inconvenient to iterate over values with a loop, inconvenient to pass a “set” into functions, and inconvenient to extend the logic. We need a structure that holds “many conceptually similar pieces of data” under one name. That structure is an array.
In programming, it’s very useful to look at things from different angles. When you see 7 values (for example, by days of the week), you can think: “these are seven separate numbers.” Or you can think: “this is one dataset that has a size and elements.” An array is exactly what trains your brain to see collections of similar things everywhere.
Let’s imagine what a workout tracker would look like without arrays. It would be something like:
fun main() {
val mon = 0
val tue = 30
val wed = 0
val thu = 45
val fri = 0
val sat = 60
val sun = 15
println("Monday minutes = $mon") // Monday minutes = 0
}
Does it work? Yes. Is it convenient? Not really anymore. And what if later you need to “loop over the days” and print all values? What if you need to find the maximum? What if you need to replace “7 days” with “30 days” (hypothetically)? That’s where arrays start winning by a landslide.
What an array is
An array is a data structure that stores a fixed number of values of one type (or its subtypes). In Kotlin, arrays are an official tool for storing many same-type values and working with them as a single object. The key word here is fixed: however many elements you specify initially is how many you’ll have.
A handy everyday analogy: an array is a box with numbered slots. The box is made at the factory, and the number of slots does not change. You can move contents between slots, you can look at what’s in a specific slot, you can go through all slots in order—but you can’t “insert another slot between 3 and 4.” The “box” does not support expansion.
The word “fixed” is worth emphasizing again, because it’s one of the most common sources of surprise. An array can’t be “expanded” the way you expand a to-do list on paper: you add an item and that’s it. If an array has 7 elements, the “eighth” won’t fit there. This is a fundamental property of arrays: the size is set at creation time and does not change.
In practice, that means: if you suddenly need more space, you create a new array and move the data. That sounds a bit scary, but later we’ll learn more convenient ways to do this. For today, it’s enough to remember the rule: an array is a “fixed box,” not a “stretchy bag.”
2. Types of arrays in Kotlin: Array and IntArray
In Kotlin, there are two families of arrays that you should know about right from the start:
- Array<T> — a generic array for objects (for example, String and any classes).
- primitive arrays (IntArray, DoubleArray, CharArray, etc.) — optimized for numbers/characters without extra overhead.
Array<T>: the generic array
Kotlin’s main “generic” array is Array<T>. It’s suitable for storing objects: strings, any classes (and later, when you have your own types, those too). The element type is written in angle brackets: Array<String>, Array<Int>, Array<Char>.
The simplest way to create such an array is arrayOf(...): you list the elements, and Kotlin builds an array from them.
Example: an array of strings via arrayOf(...)
fun main() {
val names: Array<String> = arrayOf("Ann", "Bob", "Cindy")
println("names size = ${names.size}") // names size = 3
}
Here a new important property appears right away: size. It’s the number of elements in the array. You’ll need it immediately, because all array boundaries depend on its size.
Example: Kotlin often infers the type
fun main() {
val colors = arrayOf("red", "green", "blue")
println("colors size = ${colors.size}") // colors size = 3
}
We didn’t write Array<String>—and it still came out correctly, because Kotlin inferred the type from the values. That’s convenient, but early on it’s sometimes useful to write the type explicitly, so your brain gets used to reading code “from left to right.”
Primitive arrays: IntArray, DoubleArray, CharArray
At this point, almost every beginner asks a reasonable question: “Why can’t I always use Array<T>? Why do we need IntArray, DoubleArray at all?”
The answer is: you can use Array<T>, but Kotlin specifically adds separate arrays for primitive types: IntArray, DoubleArray, CharArray, etc. The Java language, on which Kotlin was built, allows primitive types to be packed very compactly into arrays.
Elements in primitive arrays are packed more tightly than in Array<T>. Because of that optimization, they take less space and run faster. Just remember the rule: for integers in basic tasks, use IntArray, for Double — DoubleArray, for characters — CharArray. It’s easier to read and comes with fewer surprises. Kotlin explicitly treats these “primitive arrays” as separate types.
Let’s compare them head-to-head:
| What we store | Generic array | Primitive array |
|---|---|---|
| Strings | |
(no separate one) |
| Integers | |
|
| Floating-point | |
|
| Characters | |
|
Important: IntArray is not Array<Int>. They look similar in usage (they have size, you can iterate with a loop), but they are different types.
Example: an integer array via intArrayOf(...)
fun main() {
val scores: IntArray = intArrayOf(10, 20, 30)
println("scores size = ${scores.size}") // scores size = 3
}
4. Creating an array of a required size and default values
Before this, we created arrays when we already knew the specific elements. But in real tasks, it’s often the opposite: we know how many elements we need, and the values will appear later (for example, the user will enter 7 numbers, one per day of the week). For this, primitive arrays have a constructor of the form IntArray(size).
And here’s an important point: the array will be filled with default values. For Int, that is 0.
Example: create an array of 5 elements filled with zeros
fun main() {
val zeros = IntArray(5)
println("zeros size = ${zeros.size}") // zeros size = 5
for (x in zeros) {
print("$x ")
}
// 0 0 0 0 0
}
Pay attention to for (x in zeros): we iterate over the array elements “by values.” We aren’t working with indices yet (that will be the next lecture), but we can already see the contents.
5. Mini app: a weekly workout tracker
So arrays aren’t “in a vacuum,” we’ll start assembling a small console app that we’ll keep developing throughout the course. The idea is simple: we want to store workout data for a week. For now, no input, no editing, no statistics— just a scaffold of the structure. Yes, this looks a lot like real development: first we build the skeleton, then we fill in the logic.
In the first version, we will create:
- an array of weekday names (strings),
- an array of workout minutes for each day (integers),
- print how many days we have in the data to make sure the structure is assembled correctly.
Example: data scaffold (days + minutes)
fun main() {
val days: Array<String> = arrayOf("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
val minutes: IntArray = intArrayOf(0, 30, 0, 45, 0, 60, 15)
println("Days count = ${days.size}") // Days count = 7
println("Minutes count = ${minutes.size}") // Minutes count = 7
}
So far it looks like “just two arrays,” but an important idea is already visible: data of the same nature should be stored together. We’re not making monMinutes, tueMinutes, wedMinutes— we’re making one array minutes, where each position corresponds to a day of the week.
Another important point: if you have two arrays that “run in parallel” (day and minutes), their sizes must match. Otherwise, your logic will start breaking, and debugging will turn into an archaeological expedition through your code.
6. Typical mistakes when working with arrays
Mistake #1: expecting the array to “expand by itself.”
Beginners sometimes think: “well, I can assign a[10] = 5, so the array will become bigger.” No: the size is fixed, and trying to access beyond the bounds will cause a runtime error. Remember today’s mantra: an array is a fixed-size box.
Mistake #2: confusing Array<Int> and IntArray and being surprised that Kotlin won’t accept one in place of the other.
These are different types. In basic integer tasks, choose IntArray: it’s easier to read and there’s less chance of getting confused. Kotlin describes primitive arrays as separate classes.
Mistake #3: creating IntArray(n) and expecting “random values” or “emptiness.”
IntArray(n) is filled with zeros, because Kotlin guarantees a predictable initial state. That’s convenient, but if you expected something else, be sure to do an explicit fill step (we’ll cover that in later lectures).
Mistake #4: making an array out of “everything mixed together,” mixing types.
Arrays like order: one array—one type. If you feel like you “really want to mix,” most often it’s a signal that the data should be stored differently (but that’s not today’s topic). For now, stick to a simple rule: Array<String> for strings, IntArray for integers.
Mistake #5: forgetting to sanity-check the sizes of parallel arrays.
If you have two arrays that are supposed to be in sync (for example, days and minutes), they must have the same size. Otherwise, later you’ll get “the day exists but minutes don’t”— kind of like a gym membership, but without the gym.
GO TO FULL VERSION