Array Declaration in Kotlin
On this page (12sections)
Introduction
Array Declaration is a fundamental concept every Kotlin developer should understand. Arrays store a fixed number of elements in memory with fast index-based access. They are useful when size is known upfront or when interoping with Java APIs.
Arrays store multiple values of the same type in a fixed-size container. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- Arrays store multiple values of the same type in a fixed-size container.
- Use arrayOf() for inferred type or Array
for explicit declaration. - Array indices start from zero.
Syntax
val numbers = arrayOf(1, 2, 3)
Array Declaration in Kotlin Example Program in Kotlin
fun main(args: Array<String>) {
val numbers = arrayOf(10, 20, 30)
println("First: ${numbers[0]}")
println("Size: ${numbers.size}")
}
Sample Output
First: 10
Size: 3
When to use
Use arrays when you need fixed-size storage, primitive arrays without boxing overhead, or compatibility with Java vararg APIs.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
val numbers = arrayOf(10, 20, 30)assigns or updates a value used later in the program. -
The
println("First: ${numbers[0]}")statement writes a line to the console — this produces part of the sample output below. -
The
println("Size: ${numbers.size}")statement writes a line to the console — this produces part of the sample output below. -
Arrays store multiple values of the same type in a fixed-size container.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
- Prefer
listOforarrayOffactory functions over manual size allocation when possible. - Use typed arrays (
IntArray) for numeric data to avoid boxing overhead. - Bounds-check mentally: invalid indices throw
IndexOutOfBoundsException.
Common Mistakes
- Confusing
Array<Int>(boxed) withIntArray(unboxed primitives). - Assuming arrays are dynamically resizable like ArrayList — they are fixed size.
- Using reference equality (
===) when comparing array contents — usecontentEquals.
Key Points
- Arrays store multiple values of the same type in a fixed-size container.
- Use arrayOf() for inferred type or Array
for explicit declaration. - Array indices start from zero.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Semicolons at the end of statements are optional in Kotlin.