Creating arrays
- Kotlin course
- Beginner
- Lesson 53/116
- 4 min
Learn to create arrays with arrayOf and intArrayOf.
Creating arrays
An array is a fixed-size collection. In Kotlin, arrayOf creates an array of any type.
val fruits = arrayOf("apple", "pear", "cherry")
val nums = intArrayOf(3, 7, 2, 5)
println(fruits.contentToString()) // [apple, pear, cherry]arrayOf makes a general array (Array<String>). intArrayOf makes a specialized array for Ints (IntArray); it uses less memory.
To print an array's contents, use contentToString(); plain println(array) prints an address. Array size does not change after creation.
Array and IntArray
arrayOf and intArrayOf produce different types. arrayOf(1, 2, 3) gives an Array<Int>; intArrayOf(1, 2, 3) gives an IntArray.
val a = arrayOf(1, 2, 3) // Array<Int>
val b = intArrayOf(1, 2, 3) // IntArray
println(a[0]) // 1
println(b[0]) // 1Both use the same access syntax: array[index]. IntArray is primitive-based; it is more efficient for large amounts of numbers.
arrayOf is for complex types (String, objects); intArrayOf is for Ints only.
Practice Create an array and print it
Write a fun main(). Create an array with val fruits = arrayOf("apple", "pear", "cherry"). Print its contents with println(fruits.contentToString()).
Starter code
fun main() {
// Create an array and print it
}Sample solution
fun main() {
val fruits = arrayOf("apple", "pear", "cherry")
println(fruits.contentToString())
}Expected output
[apple, pear, cherry]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What type of array does arrayOf("a", "b", "c") create?
- List<String>
- IntArray
- String
- Array<String> Correct answer
Explanation: arrayOf creates an Array<String> of Strings.
2 Complete the arrayOf call
val fruits = ____("apple", "pear", "cherry")
val fruits = arrayOf("apple", "pear", "cherry")
Explanation: arrayOf("apple", ...) creates a String array.
3 Match the array creation forms
| Term | Meaning |
|---|---|
arrayOf(...) |
General array |
intArrayOf(...) |
Int array |
Array<String> |
String array type |
IntArray |
Int array type |