- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create an array in Kotlin like in Java by just 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]
- Related Articles
- How to create an empty array in Kotlin?
- How to create an Array in Java?
- How to extend the size of an array in Java
- How to define an array size in java without hardcoding?
- How to create an ArrayList from an Array in Java?
- How to create an array of Object in Java
- How to create a constructor reference for an array in Java?
- How to split a String into an array in Kotlin?
- How to create a WebView in an Android App using Kotlin?
- How to create LabelValue Tuple from an array in Java
- How to create an array of linked lists in java?
- How to create a list in Kotlin?
- How to create an instance of an anonymous interface in Kotlin?
- How to create an instance of an abstract class in Kotlin?
- How to create a generic array in java?

Advertisements