Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Open Ended Ranges



In Groovy, we can define open ended ranges which allows us to define a sequence of values where end values are not included in the range. An open ended range is also termed as exclusive range. An open ended range is different from regular range in the fact that regular range includes both start and end values.

Syntax

start..<end

Using < we define the range as open ended. Following are few examples to understand the concept better.

Example - Open Ended Range of Numbers

Following is an example of a open ended range of numbers. When we print the range, 5 is not printed.

Example.groovy

class Example { 
   static void main(String[] args) { 
       def array = 1..<5;   
	   
       println(array.toList()); 
   } 
}

Output

When we run the above program, we will get the following result −

[1, 2, 3, 4]

Example - Open Ended Range of Characters

Following is an example of a open ended range of characters. When we print the range, e is not printed.

Example.groovy

class Example { 
   static void main(String[] args) { 
       def array = 'a'..<'e';   
	   
       println(array.toList()); 
   } 
}

Output

When we run the above program, we will get the following result −

[a, b, c, d]

Example - Use of Open Ended Range in For Loop

Following is an example of a for loop based iteration of a open ended range of numbers. When we print the range, 5 is not printed.

Example.groovy

class Example { 
   static void main(String[] args) { 
       for (i in 0..<5) {
	      println i
       }
   } 
}

Output

When we run the above program, we will get the following result −

0
1
2
3
4

Exclusive Beginning in Ranges

From Groovy 4 onwards, we can define range to exclude beginning as well.

Following is an example of a open ended range of numbers with exclusive beginning.

Example.groovy

class Example { 
   static void main(String[] args) { 
       def exclusiveBeginning = 1<..5;
	   def fullyExclusive = 1<..<5;
	   
       println(exclusiveBeginning.toList());
       println(fullyExclusive.toList());	   
   } 
}

Output

When we run the above program, we will get the following result −

[2, 3, 4, 5]
[2, 3, 4]
groovy_ranges.htm
Advertisements