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

Manual Básico de Java

Controle de fluxo Java

Java Array

Java Orientação a Objetos (I)

Java Orientação a Objetos (II)

Java Orientação a Objetos (III)

Tratamento de Exceções Java

Java Lista (List)

Java Queue (Fila)

Conjunto Java Map

Conjunto Java Set

E/S Java (I/O)/O)

Reader Java/Writer

Outros tópicos do Java

Uso e exemplo do método charAt() da String Java

Java String (String) Methods

O método charAt() da String Java retorna o caractere na posição especificada.

A sintaxe do método charAt() da String Java é:

string.charAt(int index)

Parâmetro do método charAt()

  • index - Índice do caractere (valor int)

Retorno do método charAt()

  • Retorna o caractere na posição especificada (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) returns the sixth and seventh characters.

To find the index of the first occurrence of a specified character, useJava String indexOf()Methods.

Java String (String) Methods