English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Usage and examples of Java String charAt()

Java String (String) Methods

The Java String charAt() method returns the character at the specified index.

The syntax of the string.charAt() method is:

string.charAt(int index)

charAt() parameter

  • index - Character index (integer value)

Return value of charAt()

  • Return the character at the specified index (index).

Note:If the index passed to charAt() is negative or out of range, an exception will be thrown.

Example: Java String charAt() Method

class Main {
  public static void main(String[] args) {
    String str1 = "Learn Java";
    String str2 = "Learn\nJava";
    //first character
    System.out.println(str1).charAt(0)); // 'L'
    //seventh character
    System.out.println(str1.charAt(6)); // 'J'
    //sixth character
    System.out.println(str2.charAt(5)); // '\n'
  }
}

In Java, the index of a string starts from 0, not1. This is why charAt(0) returns the first character. Similarly, charAt(5) and charAt(6) to return the sixth and seventh characters.

If you need to find the index of the first occurrence of a specified character, please useJava String indexOf()Methods.

Java String (String) Methods