Question
How can I create an integer array of a specified size in Kotlin, equivalent to this Java code?
int[] a = new int[n];
In particular, how do I create an array with n integer elements, initially filled with default values?
Short Answer
Kotlin provides specialized primitive arrays such as IntArray and generic object arrays such as Array<T>. For the direct equivalent of Java's new int[n], use IntArray(n). You will also learn how to create arrays with custom initial values and when to use each array type.
Concept
Kotlin has two main array categories:
- Primitive arrays, such as
IntArray,DoubleArray, andBooleanArray, store primitive values efficiently. - Generic arrays, written as
Array<T>, store objects or nullable values.
For Java code like this:
int[] a = new int[n];
use this Kotlin code:
val a = IntArray(n)
IntArray(n) creates an array containing n integers. Every element starts as 0, matching Java's behavior for an int[].
This distinction matters because IntArray is not the same type as Array<Int>. IntArray is intended for numeric data and avoids boxing each integer into an Integer object on the JVM. In most cases, prefer IntArray when you need an array of Int values.
Mental Model
Think of an array as a row of numbered storage boxes.
When you write:
val scores = IntArray(5)
Kotlin creates five boxes numbered from 0 to 4:
index: 0 1 2 3 4
value: 0 0 0 0 0
IntArray(5) tells Kotlin how many boxes to create. Since you did not provide values, each integer box receives its default value: 0.
When you provide an initializer, you are giving Kotlin a rule for filling every box.
Syntax and Examples
Create an integer array by size:
val n = 5
val numbers = IntArray(n)
println(numbers.contentToString())
// [0, 0, 0, 0, 0]
Access or change values using zero-based indexes:
val numbers = IntArray(3)
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
println(numbers[1]) // 20
Create an IntArray with a calculated initial value for each index:
val squares = IntArray(5) { index -> index * index }
println(squares.contentToString())
// [0, 1, 4, 9, 16]
Create a generic Array<Int> instead:
val values = Array(5) { 0 }
println(values.contentToString())
// [0, 0, 0, 0, 0]
Although this looks similar, Array<Int> stores boxed Int objects on the JVM. Use it only when an API specifically requires Array<Int> or when you need nullable integers:
val answers: Array<Int?> = arrayOfNulls(3)
println(answers.contentToString())
// [null, null, null]
Step by Step Execution
Consider this code:
val size = 4
val temperatures = IntArray(size) { index -> index + 18 }
temperatures[2] = 25
println(temperatures.contentToString())
Execution trace:
sizeis assigned the value4.IntArray(size)creates four positions: indexes0,1,2, and3.- The initializer runs once per index:
- Index
0:0 + 18produces18. - Index
1:1 + 18produces19. - Index
2:2 + 18produces20. - Index
3:3 + 18produces21.
- Index
- The array is now
[18, 19, 20, 21]. temperatures[2] = 25replaces the value at index2.- The output is:
[18, 19, 25, 21]
Real World Use Cases
Arrays created by size are useful when the number of positions is known before the values are processed.
- Daily counters: Store one count for each hour of the day with
IntArray(24). - Game boards: Store a fixed grid of cells, such as a 3×3 tic-tac-toe board.
- Image or audio processing: Keep fixed-size pixel, sample, or color-channel data.
- Frequency counting: Create an array with one slot per possible category, such as digits
0through9. - Algorithm problems: Store dynamic-programming results or visited states when the maximum size is known.
Example: count occurrences of each digit in a string.
val counts = IntArray(10)
val input = "102301"
for (character in input) {
val digit = character.digitToInt()
counts[digit]++
}
println(counts.contentToString())
// [2, 2, 1, 1, 0, 0, 0, 0, 0, 0]
Real Codebase Usage
In production Kotlin code, developers choose the array type based on the data and API requirements.
Use primitive arrays for numeric storage
fun calculateTotal(prices: IntArray): Int {
var total = 0
for (price in prices) {
total += price
}
return total
}
This is a suitable use of IntArray because prices are non-null integers.
Validate a requested size first
Avoid creating arrays from invalid input:
fun createScores(size: Int): IntArray {
require(size >= 0) { "Size must not be negative" }
return IntArray(size)
}
require provides a clear error message rather than letting an invalid size reach later logic.
Use an initializer to avoid a separate filling loop
val ids = IntArray(100) { index -> index + 1 }
This is concise and makes the initialization rule clear.
Use lists when the size must grow or shrink
val activeUserIds = mutableListOf<Int>()
activeUserIds.add(42)
Arrays have a fixed length. A MutableList is often more appropriate for data collected over time.
Common Mistakes
Using Array<Int>(n) without an initializer
This does not compile:
// Broken: Array requires an initializer function.
val values = Array<Int>(5)
Use an initializer:
val values = Array(5) { 0 }
Or, for integer data, prefer:
val values = IntArray(5)
Expecting IntArray and Array<Int> to be interchangeable
They are different types:
val primitiveNumbers = IntArray(3)
val objectNumbers = Array(3) { 0 }
A function accepting IntArray cannot directly receive Array<Int>. Match the parameter type required by the function or API.
Accessing an index outside the array
val values = IntArray(3)
values[3] = 10 // Broken: valid indexes are 0, 1, and 2.
For an array of size n, valid indexes range from 0 through n - 1.
Assuming arrays can grow
val values = IntArray(2)
// values.add(10) // Broken: arrays do not have add.
Use MutableList<Int> when you need to add or remove items dynamically.
Printing an array directly
val values = IntArray(3)
println(values)
This may print an implementation-style representation rather than the contents. Use:
println(values.contentToString())
Comparisons
| Need | Recommended Kotlin type | Example |
|---|---|---|
| Fixed-size non-null integers | IntArray | IntArray(10) |
| Fixed-size non-null doubles | DoubleArray | DoubleArray(10) |
| Fixed-size booleans | BooleanArray | BooleanArray(10) |
| Fixed-size objects or strings | Array<T> | Array(3) { "" } |
| Fixed-size nullable values | Array<T?> | arrayOfNulls<String>(3) |
| A collection that can grow or shrink | MutableList<T> | mutableListOf<Int>() |
IntArray compared with Array<Int>:
| Feature | IntArray | Array<Int> |
|---|---|---|
| Stores | Primitive integer values | Int objects on the JVM |
| Default construction | IntArray(size) | Array(size) { 0 } |
| Default value | 0 | Determined by initializer |
| Nullable elements | No | Yes, with Array<Int?> |
| Best for | Numeric data and performance-sensitive loops | APIs requiring Array<Int> or nullable values |
Cheat Sheet
// Java: int[] a = new int[n]
val a = IntArray(n) // n zeros
// Set every value to the same number
val tens = IntArray(n) { 10 }
// Use the index while filling the array
val indexes = IntArray(n) { it }
// Generic object array
val names = Array(n) { "Unknown" }
// Nullable object array, filled with null
val optionalNames = arrayOfNulls<String>(n)
// Read and write
val first = a[0]
a[0] = 42
// Length
println(a.size)
// Display contents
println(a.contentToString())
Rules to remember:
IntArray(size)is the closest Kotlin equivalent to Javanew int[size].- Array indexes start at
0. - Array size is fixed after creation.
- Use
Array(size) { value }for object arrays or custom initialization. - Use
MutableListwhen the collection must change size.
FAQ
What is the Kotlin equivalent of new int[n] in Java?
Use IntArray(n). It creates n integer elements initialized to 0.
Does IntArray(n) create null values?
No. IntArray holds non-null Int values, and new elements start at 0.
How do I create an array filled with the same value in Kotlin?
Use an initializer:
val values = IntArray(5) { 7 }
This produces [7, 7, 7, 7, 7].
How do I create a Kotlin string array with a given size?
Provide an initializer value:
val names = Array(3) { "" }
For null entries, use arrayOfNulls<String>(3).
Why does Array<Int>(n) not work?
Array requires a function that supplies a value for every index. Write Array(n) { 0 }, or use IntArray(n) for integer values.
Can an IntArray be resized?
No. Its size is fixed. Create a new array, use copyOf, or choose a MutableList<Int> if resizing is required.
How can I print a Kotlin array's values?
Use contentToString():
println(values.contentToString())
Mini Project
Description
Build a small score tracker for a class. The number of students is known in advance, so an IntArray is a good fit. The program initializes each score, updates entries, and calculates the total and average.
Goal
Create and process a fixed-size integer array of student scores.
Requirements
Create an IntArray for five student scores.
Initialize its values using the array index.
Update one student's score after the array is created.
Print every score with its student number.
Calculate and print the total and average score.
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.