Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - String getAt(int index) method



getAt() method returns the character at given index.

Syntax

String getAt(int index)

Parameters

  • index − The position of the string to return.

Return Value

This method returns string value at the index position.

Example - Usage of getAt() method

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

Example.groovy

class Example {
   static void main(String[] args) {
      String a = "Hello World"; 
		
      println(a.getAt(2)); 
      println(a.getAt(6)); 
      println(a.getAt(7));  
   }
}

Output

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

l 
W 
O

Example - Usage of getAt() for invalid index

Following is an example of the usage of getAt() method with an invalid index.

Example.groovy

class Example {
   static void main(String[] args) {
      String a = "Hello World"; 
		
      println(a.getAt(a.size() + 1)); 
   }
}

Output

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

Caught: java.lang.StringIndexOutOfBoundsException: Range [12, 13) out of bounds for length 11
java.lang.StringIndexOutOfBoundsException: Range [12, 13) out of bounds for length 11

Example - Usage of getAt() method to get last character of string

Following is an example of the usage of getAt() method to get the last character of the string.

Example.groovy

class Example {
   static void main(String[] args) {
      String a = "Hello World"; 
		
      println(a.getAt(a.size() - 1)); 
   }
}

Output

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

d
groovy_strings.htm
Advertisements