
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create an Array in Kotlin Like in Java by Providing a Size
Kotlin is a cross platform statistically typed language based upon JVM. Kotlin is designed in such a way that it is interoperate fully with Java and JVM. In Java, we can simply create an array by providing a size.
Example – Array of Specific Size in Java
The following example demonstrates how to create an array of a specific size in Java.
public class MyClass { public static void main(String args[]) { int a[]=new int[5]; for(int i=0;i<=5;i++){ System.out.println(a[i]); } } }
Output
As we have created an empty array, it will have the default values of 0’s in it.
0 0 0 0 0 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at MyClass.main(MyClass.java:5)
Example – Array of Specific Size in Kotlin
In this example, we will see how we can create an array of specific size in Kotlin.
fun main(args: Array<String>) { // declaring null array of size 5 // equivalent in Java: new Integer[size] val arr = arrayOfNulls<Int>(5) print("Array of size 5 containing only null values:
") println(arr.contentToString()) val strings = Array(5) { "n = $it" } print("
Array of size 5 containing predefined values:
") println(strings.contentToString()) val arrZeros = Array(5) { 0 } print("
Array of size 5 containing predefined values:
") println(arrZeros.contentToString()) }
Output
It will generate the following output −
Array of size 5 containing only null values: [null, null, null, null, null] Array of size 5 containing predefined values: [n = 0, n = 1, n = 2, n = 3, n = 4] Array of size 5 containing predefined values: [0, 0, 0, 0, 0]
Advertisements