How to Use Ranges in Groovy

Ranges in Groovy are lists containing sequential values. A range is of type Range (from Java) and extends java.util.List. As an example, consider a demographic range for a target radio audience for ages 18 to 30. The values stored in this list would be 18,19, 20 and so on up to and including 30. We will explore this scenario in the example below.

To learn how to use ranges in Groovy follow these 3 steps:

  1. Open your text editor and type in the following lines of Groovy code:
    def targetAudienceAges = 18..30
    def sampleAge=27
    println "$targetAudienceAges"
    println "First age in range: ${targetAudienceAges.from}"
    println "Last age in range: ${}"
    if (sampleAge ≥ targetAudienceAges.from && sampleAge < {
    	println "Sample age is within target audience range"
    else {
    	println "Sample age is not within target audience range"
    println "Here are the ages in the list:"
    for (int age : targetAudienceAges) {
    	print "$age "
    The name of the range is tragetAudienceAges and contains the integers 18 up to 30. Note the from property that gives us access to the first number in the range. The to property references the last number in the range. We can verify a given integer, e.g., sampleAge, is present in the range by applying and if statement as shown in the source code. The program then prints out each age in the list.
  2. Save your file as Use.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run range script
    The output displays the integers in the list as well as the beginning and ending integers. The output verifies that the sample age is present in the range. Then the individual ages in the range are printed.
Author: Stephen Withrow

Stephen has over 30 years of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.