Scala program to create strings array

Scala array program/example: Here, we are going to learn different methods to create strings array in Scala.
Submitted by Shivang Yadav, on April 08, 2020 [Last updated : March 10, 2023]

Scala array is a collection of elements of the same data type. The data type can be string also, this is a string array.

    array = {"Hello!", "IncludeHelp", "Scala"} 

Creating a string array in Scala

You can initialize an array using the Array keyword. To know more about creating a Scala array, read: Scala Arrays

There are multiple ways to create a string array in Scala.

Method 1

If you know all elements of the array in advance, you can initialize the Scala array in the following manner.

    val arr_name = Array(element1, element2, ...) 

Scala code to create strings array (Example 1)

object myObject 
{ 
	def main(args:Array[String]) 
	{ 
	    val colors = Array("Red", "Blue", "Black", "Green")
	    println("This is an array of string :")
	    for(i <- 0 to colors.length-1){
	        println(colors(i))
	    }
	} 
} 

Output

This is an array of string :
Red
Blue
Black
Green

Method 2

If you don't know the elements of the string in advance but know the number of elements present in the array, then we will create an empty array of definite size first then feed elements to it.

    val arr_name = new Array[String](number_of_elements)

Scala code to create strings array (Example 2)

object myObject 
{ 
	def main(args:Array[String]) 
	{ 
	    val colors = new Array[String](3)
	    
	    colors(0) = "Red"
	    colors(1) = "Blue"
	    colors(2) = "Black"
	    
	    println("This is an array of string :")
	    for(i <- 0 to colors.length-1){
	        println("colors("+i+") : "+colors(i))
	    }
	} 
} 

Output

This is an array of string :
colors(0) : Red
colors(1) : Blue
colors(2) : Black

Creating Mutable Strings Array in Scala

You can create a string array even when you do not know the size and element of the array. For this, we will create a mutable string. This mutable string is created using

ArrayBuffer class whereas others were created using Array class.

To create a mutable string we need to import mutable.ArrayBuffer in your program using,

    import scala.collection.mutable.ArrayBuffer

Scala code to mutable strings Array

import scala.collection.mutable.ArrayBuffer

object myObject 
{ 
	def main(args:Array[String]) 
	{ 
	    val colors = new ArrayBuffer[String]()
	    
	    colors += "Red"
	    colors += "Blue"
	    colors += "Black"
	    colors += "Green"
	    
	    println("Mutable string array:")
	    for(i <- 0 to colors.length-1){
	        println("colors("+i+") : " + colors(i))
	    }
	} 
} 

Output

Mutable string array:
colors(0) : Red
colors(1) : Blue
colors(2) : Black
colors(3) : Green

Scala Array Programs »



Related Programs



All Scala Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.