Home »
Scala
How to print an array in Scala?
By IncludeHelp Last updated : October 20, 2024
Array in Scala
In Scala, Array is a data structure that is a collection of elements of same data type.
Creating an array
The Array keyword is used to create an array in Scala. There are multiple syntaxes to create an array. They are,
var array_name : Array[data_type] = new Array[data_type(size)
var array_name: Array[data_tpye] = new Array(size)
var array_name = new Array[data_type](size)
var array_name = Array(element1, elmenet2, element3, ...)
All the four declarations are valid but the last two are commonly used.
Accessing an element from the array
To access the element of the array, its index is used.
Syntax
array_name[index]
Printing an Array
There are two methods to print all the elements of the array (print array):
- Using iteration
- Using string conversion
Printing elements of array using iteration
We can print the elements of the array by integrating over all the elements of the array and then printing each element using their index.
Syntax
for(i <- 0 to array_name.length-1)
print(array_name[i])
Program to print array using iteration
object MyClass {
def main(args: Array[String]) {
var score = Array(97, 90, 89, 75, 45, 78, 99)
println("Elements of Array are : ")
for(i <- 0 to score.length-1 )
print(score(i) + " ")
}
}
Output
Elements of Array are :
97 90 89 75 45 78 99
Explanation
In the above code, we have created an array of integer values and then use the for loop to iterate over the elements of the array using the print statement.
Printing elements of the array using string conversion method
We can print array using the string conversion method, i.e. converting the array to a string using mkString() method.
Syntax
array_name.mkString(saperator)
Program to print array using string conversion method
object MyClass {
def main(args: Array[String]) {
var score = Array("C", "C++", "Java", "Python", "Scala")
var string = score.mkString(" , ")
println("Elements of Array are :\n" + string)
}
}
Output
Elements of Array are :
C , C++ , Java , Python , Scala
Explanation
In the above code, we have declared an array of strings. We have used the mkString() method to convert the array of string to string and then print it using the print statement.