Kotlin array length

Kotlin array length DEFAULT

Kotlin Array

next →← prev

Array is collection of similar data types either of Int, String etc. Array in Kotlinis mutable in nature with fixed size which means we can perform both read and write operations on elements of array.

Constructor of array:

Array constructor is declared with specified size and init function. The init function is used to returns the elements of array with their index.

Kotlin Array can be created using arrayOf(), intArrayOf(), charArrayOf(), booleanArrayOf(), longArrayOf(), shortArrayOf(), byteArrayOf() functions.

Kotlin array declaration - using arrayOf() function

Kotlin array declaration - using intArrayOf() function

Modify and access elements of array

Kotlin has set() and get() functions that can direct modify and access the particular element of array respectively.

The set() function is used to set element at particular index location. This is also done with assigning element at array index. Array get() function is used to get element from specified index.

Kotlin array set() function example

Output:

Kotlin array get() function example

Output:

Kotlin Array Example 1:

In this example, we are simply initialize an array of size 5 with default value as 0 and traverse its elements. The index value of array starts from 0. First element of array is placed at index value 0 and last element at one less than the size of array.

Output:

Kotlin Array Example 2:

We can also rewrite the value of array using its index value. Since, we can able to modify the value of array, so array is called as mutable property.

For example:

Output:

Kotlin Array Example 3 - using arrayOf() and intArrayOf() function:

Array in Kotlin can also be declared using library functions such as arrayOf(), intArrayOf(), etc. Let's see the example of array using arrayOf() and intArrayOf() function.

Output:

Ajay Prakesh Michel John Sumit 1 10 4 6 15 5 10 20 12 15 1 10 4 Ajay Prakesh 5 10 15 20 25

Kotlin Array Example 4

Suppose when we try to insert an element at index position greater than array size then what will happen?

It will throw an ArrayIndexOutOfBoundException. This is because the index value is not present at which we tried to insert element. Due to this, array is called fixed size length. For example:

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at ArrayListKt.main(Array.kt:4)

Kotlin Array Example 5 - traversing using range:

The Kotlin's array elements are also traversed using index range (minValue..maxValue) or (maxValue..minValue). Let's see an example of array traversing using range.

Output:

5 10 20 12 15 5 10 20 12 15

Next TopicKotlin String



← prevnext →



Sours: https://www.javatpoint.com/kotlin-array

Kotlin Array Size

Kotlin Array Size

To get size of Array, or say number of elements in Array, read the size property of the Array object.

We can also use count() function of the Array class to get the size. We will go through an example to get the size of the Array using count() function.

In this tutorial, we will learn how to get the size of the Array using size property of Array class.

The syntax to get size of Array , in Kotlin is

arr.size

Examples

In the following example, we create a Kotlin Array with some elements, and find its size using the Array.size property.

Main.kt

fun main(args: Array<String>) { val arr = arrayOf(2, 4, 6, 8, 10) val length = arr.size println("Array size is: $length") }

Output

Array size is: 5

Now, let us take an Array of strings, with three elements in it. We find out this Array size programmatically using Array.size property.

Main.kt

fun main(args: Array<String>) { val arr = arrayOf("a", "b", "c") val length = arr.size println("Array size is: $length") }

Output

Array size is: 3

We now use count() function on Array object, and find its size.

Main.kt

fun main(args: Array<String>) { val arr = arrayOf("a", "b", "c") val length = arr.count() println("Array size is: $length") }

Output

Array size is: 3

Conclusion

In this Kotlin Tutorial, we learned how to get the size of an Array using Array.size property, with the help of examples.

❮ PreviousNext ❯

Most Read Articles

Top 50 Kotlin Interview QuestionsHow to Learn Programming? Best GuidelinesKotlin Android Tutorial - Learn Android Development with KotlinAndroid Game Development Basics

Sours: https://www.tutorialkart.com/kotlin/kotlin-array-size/
  1. Reel industries
  2. Advance auto generators
  3. Lilah ray roloff
  4. Sarina phone cases

This post will discuss how to declare and initialize an array in Kotlin with a specific value.

1. Using function

To create an in Kotlin, you can use the library function and pass the desired values to it. This is demonstrated below:

fun main(){

    val arr=arrayOf(1,2,3,4,5)

    println(arr.contentToString())    // [1, 2, 3, 4, 5]

}

Download Code

2. Using Constructor

Another option is to use the Array constructor, which takes the array size and the function that can return the initial value of each array element given its index.

The following code creates an of of size 5 with all values initialized with a constant.

fun main(){

    val arr=Array(5){1}

 

    println(arr.contentToString())    // [1, 1, 1, 1, 1]

}

Download Code

 
To create an array with values initialized to their index value, you can use the following code:

fun main(){

    val arr=Array(5){it}

 

    println(arr.contentToString())    // [0, 1, 2, 3, 4]

}

Download Code

3. Primitive type arrays

Kotlin offers specialized classes to represent arrays of primitive types such as , , , etc. To initialize primitive arrays with a specific value, you can use the class constructor with lambda.

For example, creates an integer array of size and initializes it with a value of .

fun main(){

    val arr=IntArray(5){1}

 

    println(arr.contentToString())    // [1, 1, 1, 1, 1]

}

Download Code

 
Alternatively, you can create primitive type array in Kotlin with desired values using factory function , , , , etc.

fun main(){

    val arr:IntArray=intArrayOf(1,2,3,4,5)

}

Download Code

4. Using function

The function returns an array of objects of the given type with the given size, initialized with values.

fun main(){

    val arr=arrayOfNulls<Int>(5)

 

    println(arr.contentToString())    // [null, null, null, null, null]

}

Download Code

5. Using function

Kotlin allows having arrays of size using the function. Since it’s an empty array, it throws an if you try to read or assign elements.

fun main(){

    val arr=emptyArray<Int>()

    println(arr.contentToString())        // []

}

Download Code

That’s all about declaring and initializing an array in Kotlin.

 
Reference:Basic Types: Numbers, Strings, Arrays – Kotlin Programming Language




Thanks for reading.

Please use our online compilerto post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding🙂



Sours: https://www.techiedelight.com/declare-initialize-array-kotlin/
Kotlin for Beginners - Part 9 - ARRAYS

Kotlin Array

Output:

1 2 3 4 5 10 20 30 40 50

Using the Array constructor –

Since Array is a class in Kotlin, we can also use the Array constructor to create an array.
The constructor takes two parameters:

  1. The size of the array, and
  2. A function which accepts the index of a given element and returns the initial value of that element.

Syntax:

val num = Array(3, {i-> i*1})

In the above example, we pass the size of the array as 3 and a lambda expression which initializes the element values from 0 to 9.

Kotlin program of creating array using constructor –

Output:



0 1 2 3 4

Apart from these, Kotlin also has some built-in factory methods to create arrays of primitive data types, such as byteArray, intArray, shortArray, etc. These classes do not extend the Array class; however, they implement the same methods and properties.

For example, the factory method to create an integer array is:

val num = intArrayOf(1, 2, 3, 4)

Other factory methods available for creating arrays:

  • byteArrayOf()
  • charArrayOf()
  • shortArrayOf()
  • longArrayOf()

Accessing and modifying arrays –

So far, we have seen how to create and initialize an array in Kotlin. Now, let’s see how to access and modify them.
Again, there are two ways of doing this:

    Using and methods –

    As you know, an array in Kotlin is basically a class. Therefore, we can access the data of a class object via its member functions. The and functions are said to be member functions.

    The method takes a single parameter—the index of the element and returns the value of the item at that index.
    Syntax:

    val x = num.get(0)

    The method takes 2 parameters: the index of the element and the value to be inserted.
    Syntax:

    num.set(1, 3)

    The above code sets the value of the second element in the array to 3

    Using the index operator [ ] –



    The operator can be used to access and modify arrays.
    To access an array element, the syntax would be:

    val x = num[1]

    This will assign the value of the second element in num to x.

    To modify an array element, we should do:

    num[2] = 5;

    This will change the value of the third element in the num array to 5.

    Note: Internally, the index operator or [ ] is actually an overloaded operator (see operator overloading) and only stands for calls to the and member functions.

    Here is a working example of Kotlin array manipulation in which we create an array, modify its values, and access a particular element:

     

     

    Output:

    10 6

    Traversing Arrays –

    One important property of an array is that it can be traversed programmatically, and each element in the array can be manipulated individually. Kotlin supports few powerful ways to traverse array.

    The simplest and most commonly used idiom when it comes to traversing an array is to use the for-loop.
    Syntax:

    for(i in num.indices){ println(num[i]) }

    Kotlin program of array traversal using for loop-



    Output:

    10 6 3 4 5

    Alternatively, we can use the range to achieve the same effect. In Kotlin, a range is an interval between two values (start and end) and can be created using the (..) operator. Traversal through the range can be then done using the in keyword.
    Syntax for range:

    for (i in 0..10){ println(i) }

    The range of elements in an array is defined from 0 to size-1. So, to traverse an array using range, we run a loop from 0 to size-1 on the array name.
    Kotlin program of array traversal using range-

    Output:

    1 2 3 4 5

    Another arguably less tedious, way to do the above is using the foreach loop.

    Syntax:

    arrayname.forEach({index->println(index)})

    Kotlin program of array traversal using foreach loop-

    Output:

    1 2 3 4 5


Sours: https://www.geeksforgeeks.org/kotlin-array/

Array length kotlin

An array is used to store similar data type values in a single variable. For example, you may create fifty integer or string type variables and store a value in each.

Alternatively, you may create a single array of int or string type and store fifty values in it.

A few main points about Kotlin arrays:

  • The array class represents an array in Kotlin.
  • The array class has get and set functions.
  • The array class also has the size property.
  • Just like in Java, the items in the Kotlin array are called elements.
  • Elements in the array can be accessed by index number.
  • The index starts at zero.
  • Kotlin arrays also have a few other useful member functions.

How to create an array in Kotlin?

You may create arrays in different ways:

By using the library function

You may use arrayOf() library function for creating an array. For example:

var NumArray = arrayOf(1,2,3,4,5)

Similarly, you may use a specific type of library function for creating an array. These include:

  • charArrayOf()
  • booleanArrayOf()
  • byteArrayOf()
  • intArrayOf()
  • longArrayOf()
  • shortArrayOf()

You may also create an array as follows:

var arrNum = IntArray(size)

Or

An int array can also be created like this:

var arrNum = Array(size, { 0 } )

The following section gives more detail about how to create, initialize and access array elements in Kotlin with complete code. The examples also include using a few useful array functions.

An example of using arrayOf() function

In the first example of Kotlin arrays, I am using arrayOf() library function for creating an array that contains five integer type elements.

This is followed by using a for loop for accessing those array elements:

fun main(args:Array<String>){

 

//Array Demo

 

varNumArr=arrayOf(5,10,15,20,25)

 

for(item inNumArr){

 

println(item)

 

}

 

 

 

}


The output:

5

10

15

20

25

The example of a string array by arrayOf function

The example below initializes an array of strings by using the arraOf() function. Notice, how the string data type is specified in the code below.

Again, I iterated through that array by using a for loop for displaying its items:

fun main(args:Array<String>){

 

//Array Demo

 

varArrCities=arrayOf<String>("New York","London","Dubai")

 

for(item inArrCities){

 

println(item)

 

}

 

}


The result:

New York

London

Dubai

Accessing array elements by index example

Just like in Java, the index of array elements in Kotlin starts at zero. The example below shows accessing the array elements by index number:

fun main(args:Array<String>){

 

//Array Demo

 

varArrCountriies=arrayOf<String>("USA","UK","UAE")

 

 

 

println("The country name at 0 index: "+ArrCountriies[0])

 

}


The output:

The country name at 0 index: USA

The example of array get() function

Now let us look at a few useful array functions and property in Kotlin. The first is the get() function that is used to return the array element at the specified index.

It takes an argument which is the index number (int type). The example below shows using the get() function for accessing an element:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

fun main(args:Array<String>){

 

//Array get() Demo

 

varArrNames=arrayOf<String>("Mike","Tina","Tipu","Naman")

 

 

 

println("0 index: "+ArrNames.get(0))

 

println("1 index: "+ArrNames.get(1))

 

println("2 index: "+ArrNames.get(2))

 

println("3 index: "+ArrNames.get(3))

 

}


The output:

Kotlin array

The example of set() function

The set() function is used to set the array element value at the specified index position. It takes two arguments; first is the index and the other is the value to be set.

operator fun set(index: Int, value: T)

The example below shows how to use this function. I have created an array of four elements of string type. By using the set() function, I will modify the third element value:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

fun main(args:Array<String>){

 

//Array set() Demo

 

varArrLangs=arrayOf<String>("Kotlin","Java","Python","PHP")

 

 

 

//before set funciton

 

for(item inArrLangs){

 

println(item)

 

}

 

 

 

ArrLangs.set(2,"JavaScript")

 

//after set function

 

println("#######################")

 

println("After using set function:")

 

println("#######################")

 

for(item inArrLangs){

 

println(item)

 

}

 

}


The result:

Kotlin array set

The count function example

The count function returns the number of elements in thisarray. See the example below for its usage:

fun main(args:Array<String>){

 

//Array count() Demo

 

varArrlongs=arrayOf<Long>(1,2,3,5,66656,54334,

 

344545,6555543,4545454,232,3223,23443,23232,34343,434334,3434,343,43,44)

 

 

 

println("Total elements in the array: "+Arrlongs.count())

 

 

 

}


The output:

Total elements in the array: 19

A distinct function example

If you require to get the list of distinct elements in an array then use the distinct() function. An array is specified and distinct() returns the list of unique items.

The example below contains duplicate elements. I used distinct function and see how it returns the list of unique items:

fun main(args:Array<String>){

 

//Array count() Demo

 

varArrNums=arrayOf<Int>(5,4,3,2,3,5,1)

 

varArrChar=arrayOf<Char>('z','d','y','z','t','d')

 

println("Unique elements in ArrNum: "+ArrNums.distinct())

 

println("Unique elements in ArrChar: "+ArrChar.distinct())

 

}


The output of the above code:

Unique elements in ArrNum: [5, 4, 3, 2, 1]

Unique elements in ArrChar: [z, d, y, t]

drop and dropLast functions

The drop function returns a list of elements in the array except for the first n elements. The n is an integer value that you specify for removing the first elements.

Similarly, the dropLast returns a list of array elements except for the n from the last. See the example of both functions below:

fun main(args:Array<String>){

 

//Array drop() and dropLast Demo

 

varArrNums=arrayOf<Int>(5,10,15,20,25,30,35,40,45,50)

 

 

 

println("After drop with 3 value: "+ArrNums.drop(3))

 

println("After dropLast with 3 value: "+ArrNums.dropLast(3))

 

}


The output of the above code:

After drop with 3 value: [20, 25, 30, 35, 40, 45, 50]

After dropLast with 3 value: [5, 10, 15, 20, 25, 30, 35]

first and last functions example

The first() function of the array returns the first element while the last() returns the last element of the array. Have a look at the example of both:

fun main(args:Array<String>){

 

//Array drop() and dropLast Demo

 

varArrNums=arrayOf<Int>(10,20,30,40,50)

 

 

 

println("First element in array: "+ArrNums.first())

 

println("Last element of array: "+ArrNums.last())

 

}


Output:

First element in array: 10

Last element of array: 50

An example of the size property

The size is a property of an array. It returns the total number of elements in the array. See the example code for its usage:

fun main(args:Array<String>){

 

//Array drop() and dropLast Demo

 

varArrChar=arrayOf<Char>('a','e','i','o','u')

 

 

 

println("The size of array: "+ArrChar.size)

 

}


Result:

The size of array: 5

Sorting the array by sort() function

The sort() function is used to sort a range in the array in place. For example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

fun main(args:Array<String>){

 

//Array drop() and dropLast Demo

 

varArrNum=arrayOf<Int>(50,5,25,16,21,1,100)

 

println("###########Before Sorting Array#########")

 

for(item inArrNum){

 

println(item)

 

}

 

println("###########After Sorting Array#########")

 

ArrNum.sort(0,6)

 

for(item inArrNum){

 

println(item)

 

}

 

}


The output:

Kotlin array sort

You may learn more about the array functions in the Kotlin official website here.

Sours: https://www.jquery-az.com/kotlin-array/
Arrays in Kotlin - Kotlin Tutorial for Beginners

.

You will also like:

.



1368 1369 1370 1371 1372