Question
In Java, you can initialize an array like this:
int numbers[] = new int[] {10, 20, 30, 40, 50};
How do you initialize an array with values in Kotlin?
Short Answer
By the end of this page, you will understand how to create arrays in Kotlin using predefined values, when to use arrayOf(...), when to use primitive array types like intArrayOf(...), and how Kotlin array syntax differs from Java.
Concept
Kotlin supports arrays, but its syntax is different from Java.
In Java, array creation often uses a type followed by square brackets and a new expression. Kotlin does not use new, and array creation is usually done through functions such as arrayOf(...).
For example:
val numbers = arrayOf(10, 20, 30, 40, 50)
This creates an Array<Int>.
However, Kotlin also has primitive array types for better performance:
IntArrayDoubleArrayBooleanArrayCharArrayLongArrayFloatArrayShortArrayByteArray
So if you specifically want an array of primitive Int values, Kotlin commonly uses:
val numbers = intArrayOf(10, 20, 30, 40, 50)
This matters because Kotlin distinguishes between:
Array<Int>→ array of boxedIntobjectsIntArray→ array of primitiveintvalues
In real programs, choosing the right one can affect performance, interoperability with Java, and API expectations.
A key idea is that Kotlin prefers factory functions instead of special syntax for many object creations. Arrays are a good example of that style.
Mental Model
Think of a Kotlin array as a row of numbered boxes.
- Each box has a position:
0,1,2, and so on. - You can fill the boxes with values when you create the array.
arrayOf(...)is like saying: "Create a row of boxes and put these items in them."intArrayOf(...)is like saying: "Create a row of integer boxes specifically forIntvalues."
So instead of Java's new int[] {...}, Kotlin says: "Use this array-building function and provide the values."
Syntax and Examples
Basic array initialization
val numbers = arrayOf(10, 20, 30, 40, 50)
This creates an Array<Int>.
Primitive integer array
val numbers = intArrayOf(10, 20, 30, 40, 50)
This creates an IntArray.
String array
val names = arrayOf("Alice", "Bob", "Charlie")
This creates an Array<String>.
Accessing values
val numbers = intArrayOf(10, 20, 30)
println(numbers[0]) // 10
println(numbers[1]) // 20
Creating an array by size and initializer
val squares = Array(5) { index -> index * index }
println(squares.joinToString()) // 0, 1, 4, 9, 16
This creates an array with 5 elements. Each value is generated from its index.
Which one should beginners use?
- Use
arrayOf(...)for general-purpose object arrays. - Use
intArrayOf(...)and other primitive array types when you specifically want primitive arrays. - If you are working with collections often, remember that Kotlin developers also commonly use
listOf(...), which is different from arrays.
Step by Step Execution
Consider this example:
val numbers = intArrayOf(10, 20, 30)
println(numbers[0])
println(numbers[2])
Step by step:
intArrayOf(10, 20, 30)creates an array containing three integers.- The array is stored in the variable
numbers. numbers[0]reads the first element, which is10.println(numbers[0])prints10.numbers[2]reads the third element, which is30.println(numbers[2])prints30.
Output:
10
30
Here is another traceable example:
val values = Array(4) { index -> index + 1 }
println(values.joinToString())
What happens:
Array(4)means the array will have 4 elements.- The initializer runs once for each index.
- When
indexis0, value becomes1. - When
indexis1, value becomes2. - When
indexis2, value becomes3. - When
indexis3, value becomes4. - The final array is
[1, 2, 3, 4]. joinToString()converts it to a readable string for printing.
Real World Use Cases
Arrays in Kotlin are useful when you need fixed-size indexed data.
Common examples
- Storing numeric data such as scores, coordinates, or sensor readings
- Working with Java APIs that expect arrays
- Processing command-line arguments or fixed sets of values
- Image or audio data where indexed access matters
- Performance-sensitive code using primitive arrays like
IntArray
Example: fixed monthly sales values
val sales = intArrayOf(120, 150, 90, 200)
println(sales[3]) // 200
Example: passing arrays to functions
fun printNames(names: Array<String>) {
for (name in names) {
println(name)
}
}
val team = arrayOf("Ana", "Ben", "Chris")
printNames(team)
Example: generated values
val evenNumbers = IntArray(5) { it * 2 }
println(evenNumbers.joinToString()) // 0, 2, 4, 6, 8
Real Codebase Usage
In real Kotlin codebases, arrays are used less often than lists, but they are still important.
Common patterns
Interoperating with Java
Many Java libraries use arrays in method parameters or return types.
val args = arrayOf("--debug", "--port=8080")
Using primitive arrays for performance
If a program handles many numeric values, developers often prefer primitive arrays.
val temperatures = DoubleArray(7)
Initializing from known constants
Configuration-like values may be stored in arrays when the size is fixed.
val supportedCodes = arrayOf("en", "es", "fr")
Transforming data for APIs
Developers may build arrays from collections before calling functions that require arrays.
val namesList = listOf("Alice", "Bob")
val namesArray = namesList.toTypedArray()
Guarding against invalid access
Because arrays are index-based, developers often validate indices before use.
fun safeRead(values: IntArray, index: Int): Int? {
return if (index in values.indices) values[index] else null
}
Common Mistakes
1. Expecting Java syntax to work in Kotlin
Broken code:
val numbers = new int[] {10, 20, 30}
Why it fails:
- Kotlin does not use
new. - Kotlin does not use Java's array literal syntax.
Correct version:
val numbers = intArrayOf(10, 20, 30)
2. Confusing Array<Int> with IntArray
val a = arrayOf(1, 2, 3) // Array<Int>
val b = intArrayOf(1, 2, 3) // IntArray
These are not the same type.
Avoid this mistake by checking what a function expects.
3. Using the wrong constructor style
Broken idea:
val numbers = Array<Int>(5)
Why it fails:
Arrayneeds both a size and an initializer function.
Correct version:
val numbers = Array(5) { 0 }
4. Accessing an index that does not exist
Broken code:
val numbers = intArrayOf(10, 20, 30)
println(numbers[3])
Why it fails:
- Valid indices are
0,1, and2.
Safer approach:
if (3 in numbers.indices) {
println(numbers[3])
}
5. Assuming arrays grow automatically
Arrays have fixed size after creation.
If you need a resizable structure, use a list such as mutableListOf(...) instead.
Comparisons
Arrays in Kotlin compared
| Concept | Syntax | Size | Typical use |
|---|---|---|---|
Array<T> | arrayOf(1, 2, 3) | Fixed | General object values |
IntArray | intArrayOf(1, 2, 3) | Fixed | Primitive integers, better performance |
List<T> | listOf(1, 2, 3) | Read-only interface | Most everyday Kotlin code |
MutableList<T> | mutableListOf(1, 2, 3) | Resizable | When elements need to be added or removed |
Array<Int> vs IntArray
| Feature | Array<Int> | IntArray |
|---|---|---|
| Stores | boxed Int objects | primitive int values |
| Created with | arrayOf(...) | intArrayOf(...) |
| Performance | usually less efficient for heavy numeric work | usually better for numeric work |
| Generic | yes | no |
Kotlin arrays vs Java arrays
| Java | Kotlin |
|---|---|
new int[] {1, 2, 3} | intArrayOf(1, 2, 3) |
new String[] {"a", "b"} | arrayOf("a", "b") |
new int[5] | IntArray(5) |
new String[5] | arrayOfNulls<String>(5) or Array(5) { ... } |
Cheat Sheet
Quick syntax
val a = arrayOf(1, 2, 3) // Array<Int>
val b = intArrayOf(1, 2, 3) // IntArray
val c = arrayOf("a", "b") // Array<String>
val d = Array(3) { it * 10 } // Array<Int>: [0, 10, 20]
val e = IntArray(3) { it + 1 } // IntArray: [1, 2, 3]
Rules to remember
- Kotlin does not use
newfor arrays. arrayOf(...)creates a generic object array.intArrayOf(...)creates a primitive integer array.- Arrays have fixed size.
- Indexing starts at
0. - Use
array[index]to read or update values.
Useful helpers
println(arr.size)
println(arr.indices)
println(arr.joinToString())
Common primitive array creators
intArrayOf(...)doubleArrayOf(...)booleanArrayOf(...)charArrayOf(...)longArrayOf(...)
When to use lists instead
Use listOf(...) or mutableListOf(...) when you want collection-style operations or a resizable structure.
FAQ
How do you initialize an array in Kotlin with values?
Use arrayOf(...) for general arrays or intArrayOf(...) for primitive integers.
val numbers = intArrayOf(10, 20, 30)
What is the Kotlin equivalent of new int[] { ... } in Java?
The closest Kotlin equivalent is:
val numbers = intArrayOf(10, 20, 30)
Should I use arrayOf or intArrayOf in Kotlin?
Use arrayOf(...) for generic object arrays. Use intArrayOf(...) when you need an IntArray with primitive integers.
Are Kotlin arrays fixed size?
Yes. Once created, an array's size cannot change.
What is the difference between Array<Int> and List<Int> in Kotlin?
Array<Int> is a fixed-size indexed structure. List<Int> is a collection interface and is more commonly used in everyday Kotlin code.
How do I create an empty array in Kotlin?
For a generic empty array:
val empty = emptyArray<String>()
For primitive integers:
val emptyInts = intArrayOf()
Can I create an array with generated values in Kotlin?
Yes.
val values = Array(5) { it * 2 }
Mini Project
Description
Build a small Kotlin program that stores a week's daily temperatures in an array and prints useful information. This project demonstrates how to initialize arrays with values, access elements by index, and iterate through array contents.
Goal
Create a Kotlin program that initializes an array with temperature values and prints the first, last, and all temperatures.
Requirements
- Create an integer array containing 7 temperature values.
- Print the first temperature using index access.
- Print the last temperature using its index.
- Loop through the array and print every temperature.
- Print the full array in a readable format.
Keep learning
Related questions
Accessing Kotlin Extension Functions from Java
Learn how Kotlin extension functions are compiled and how to call them correctly from Java with clear examples and common pitfalls.
Add a Maven Repository URL in Gradle Kotlin DSL (build.gradle.kts)
Learn how to add Maven Central and a custom Maven repository URL in Gradle Kotlin DSL using build.gradle.kts syntax.
Allow HTTP and HTTPS in Android 9 Pie with Network Security Configuration
Learn how Android 9 Pie handles cleartext HTTP traffic and how to allow HTTP and HTTPS safely using network security config.