Array Data Types in Java and Kotlin with Examples and Differences

Introduction

An array is a collection used to store multiple values of the same type. Arrays are fixed-size structures in both Java and Kotlin, and they provide fast access to elements using an index.


Array Overview

Feature Java Kotlin Description
Type Array of primitives or objects (int[], String[]) IntArray, Array<String> Stores multiple elements of the same type
Size Fixed Fixed Size determined at creation and cannot be changed
Access Index-based (0 to n-1) Index-based (0 to n-1) Elements accessed using indices
Mutable Yes (can change element values) Yes Elements can be updated but array size is fixed

1. Array in Java

Java arrays can hold either primitives or objects. Array size is fixed, but elements can be updated.

Java Example – Integer Array

Note: In Java, arrays use zero-based indexing. The first element is at index 0, the second at 1, and so on.


int[] numbers = {10, 20, 30, 40};

// Access elements
System.out.println(numbers[0]); // prints 10 (first element)
System.out.println(numbers[1]); // prints 20 (second element)

// Update elements
numbers[2] = 35;
System.out.println(numbers[2]); // prints 35

Java Example – String Array


String[] fruits = {"Apple", "Banana", "Cherry"};
System.out.println(fruits[2]); // Cherry

2. Array in Kotlin

Kotlin provides specialized arrays for primitives and a generic Array<T> for objects. Array size is fixed but elements are mutable.

Kotlin Example – IntArray


val numbers = intArrayOf(10, 20, 30, 40)
println(numbers[0])
numbers[1] = 25
println(numbers[1])

Kotlin Example – Generic Array


val fruits = arrayOf("Apple", "Banana", "Cherry")
println(fruits[2])

Java vs Kotlin – Array Differences

Feature Java Kotlin
Primitive Array Yes (int[], double[]) Yes (IntArray, DoubleArray)
Generic Array Yes (String[]) Yes (Array<T>)
Access Syntax arr[index] arr[index]
Null Safety No Yes
Size Mutability Fixed Fixed

Interview Questions & Answers

Q1. How do you declare an array in Java and Kotlin?

Answer: Java: int[] numbers = {1,2,3}; Kotlin: val numbers = intArrayOf(1,2,3)

Q2. Can array size be changed after creation?

Answer: No. Arrays are fixed-size, but elements can be updated.

Q3. What is the difference between IntArray and Array<Int> in Kotlin?

Answer: IntArray is optimized for primitives, Array<Int> is generic and boxed.

Q4. How do you access array elements?

Answer: Using index notation: arr[index] in both Java and Kotlin.


Conclusion

Arrays are essential for storing multiple values efficiently. Kotlin enhances Java arrays with type safety and null safety while keeping similar access syntax, making it easy to transition between Java and Kotlin.


Comments

Popular posts from this blog

Data Types - Java, Kotlin

Integer Data Types in Java and Kotlin (Byte, Short, Int, Long) with Examples

Floating Point Data Types in Java and Kotlin (Float vs Double) Explained