Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Range get() method



get() method returns the element at the specified position in this Range.

Syntax

Object get(int index)

Parameters

index − The index value to get from the range.

Return Value

Returns the range value at the particular index.

Example - Getting a value from a range of numbers

Following is an example of the usage of get() method.

Example.groovy

class Example { 
   static void main(String[] args) { 
      // range of numbers
      def array = 1..10; 
		
      println(array.get(2)); 
      println(array.get(4));     
   } 
}

Output

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

3
5

Example - Using negative index with get() method

Following is an example of the usage of get() method.

Example.groovy

class Example { 
   static void main(String[] args) { 
      // range of characters
      def array = 'a'..'z'; 
		
      println(array.get(2)); 
      println(array.get(-5));     
   } 
}

Output

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

Caught: java.lang.IndexOutOfBoundsException: Index: -5 should not be negative
java.lang.IndexOutOfBoundsException: Index: -5 should not be negative

Example - Using invalid index with get() method

Following is an example of the usage of get() method.

Example.groovy

class Example { 
   static void main(String[] args) { 
      // range of numbers
      def array = 1..10; 
		
      println(array.get(2)); 
      println(array.get(11));     
   } 
}

Output

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

Caught: java.lang.IndexOutOfBoundsException: Index: 11 too big for range: 1..10
java.lang.IndexOutOfBoundsException: Index: 11 too big for range: 1..10
groovy_ranges.htm
Advertisements