Java.lang.String.charAt() Method

Advertisements


Description

The java.lang.String.charAt() method returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

Declaration

Following is the declaration for java.lang.String.charAt() method

public char charAt(int index)

Parameters

  • index -- This is the index of the char value.

Return Value

This method returns the char value at the specified index of this string. The first char value is at index 0.

Exception

  • IndexOutOfBoundsException -- if the index argument is negative or not less than the length of this string.

Example

The following example shows the usage of java.lang.String.charAt() method.

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

  public static void main(String[] args) {
  
    String str = "This is tutorialspoint";
                   
    // prints character at 1st location
    System.out.println(str.charAt(0));
          
    // prints character at 5th location i.e white-space character
    System.out.println(str.charAt(4));
          
    // prints character at 18th location 
    System.out.println(str.charAt(17));
  }
} 

Let us compile and run the above program, this will produce the following result.It will also print white-space character.

T

p



Advertisements
Advertisements