Grails Cookbook - A collection of tutorials and examples

Groovy Array Length

Array manipulation is common in any programming language. Here is a sample code on how to get the the length of an array in Groovy.

Groovy Array Length

Here is an example of how to declare an array in Groovy:

def test = new String[3]
test[0] = "Apple"
test[1] = "Banana"
test[2] = "Carrots"

And here is another alternative for declaring an array:

String[] test = ["Apple", "Banana", "Carrots"] as String[]

Or just simply:

String[] test = ["Apple", "Banana", "Carrots"] 

Getting the length of this array is similar to Java syntax:

String[] test = ["Apple", "Banana", "Carrots"] 
def arrayLength = test.length
println "The length of the array is: " + arrayLength

Groovy also adds the size() method to an array object. We can use this to get the Groovy's array length also

String[] test = ["Apple", "Banana", "Carrots"] 
def arrayLength = test.size()
println "The length of the array is: " + arrayLength

To summarize, as of this writing, there are two ways to get the length of an array in Groovy. One is to use the length property and the other is to invoke the size() function.