Java String charAt() method
It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1.
public char charAt (int index)
It accepts only one parameter that is the index of the character.
charAt() method returns char value present at the specified index in the string.
Throws:
The method throws IndexOutOfBoundsException if index is negative or greater than the length of the string.
Метод charAt() в Java
Есть множество базовых методов, которые мы регулярно используем, даже не задумываясь. Ну а что, если задуматься и посмотреть, каким образом реализованы некоторые простые, на первый взгляд, методы? Думаю, это поможет нам стать на шаг ближе к Java) Представим ситуацию, в которой нам нужно вытащить определенный символ в какой-то строке. Как мы это можем сделать в Java? Например, с помощью вызова метода Java String charAt . О методе charAt() мы и поговорим в сегодняшней статье.
Синтаксис
Пример
Что “под капотом”

Как же оно работает, спросите вы?Дело в том, что в каждом объекте String есть массив byte с байтами элементов данной строки: А вот и сам метод chatAt : isLatin1 — флаг, указывающий на то, есть ли в нашей строке только латинские символы или нет. От это зависит, какой метод будет вызываться далее.
isLatin1 = true
- & расширяет для двоичной операции для byte побитово
- 0xff ничего не делает, но & требует аргумент
- (char) приводит данные по таблице ASCII к char
isLatin1 = false
- для ‘а’ это пара байтов — 48 и 4;
- для ‘в’ — 50 и 4.
В примере с строкой «абвг» , шестой байт — 51 — так бы и остался, но при этом увеличивается индекс до 7.
И если у нас это был байт 4, который имеет двоичное представление — 00000000 00000100, то после сдвига на 8 битов у нас будет 00000100 00000000. Если целым числом — 1024.
И если у нас были байты 51 и 1024, которые в двоичном представлении выглядели как 00000000 00110011 и 00000100 00000000, то после операции OR мы получим 00000100 00110011, что значит число 1075 в десятичной системе.
Ну и в конце концов, переводится число 1075 в тип char, а при переводе int -> char используется таблица ASCII, и в ней под номером 1075 стоит символ ‘г’.
charAt() в Java
chartAt (int index) — возвращает символ, стоящий на определенном индексе. Напомним, индексы начинаются с 0.
Синтаксис:
Лучше всего показать как это работает на примере.
Пример
Если вы запустите этот код на своем компьютере, то в консоли Вы увидите следующее:
Буква 0 индекса это: О
Буква 5 индекса это: ю
Буква 9 индекса это: ы
Комментарии к коду:
В переменную типа char мы присвоили значение 0-го индекса. 0 индекс переменной sentence — это буква «O».
В переменную типа char мы присвоили значение 5-го индекса. 5 индекс переменной sentence — это буква «ю».
В переменную типа char мы присвоили значение 9-го индекса. 9 индекс переменной sentence — это буква «ы».
Данная статья написана Vertex Academy. Есть возможность пройти обучения на наших курсах по Java с нуля. Детальнее на сайте.
Charat in Java
The method charAt() in java can be defined as the inbuilt method that returns the character value at the stated index number when searched in a string.
Syntax of charAt() in Java
The syntax of the charAt() in Java is as follow:
where string can be described as an object belonging to the String class.
Parameters of charAt() in Java
The charAt() method in java has the paramter as index.
index: The index is defined as the place of the character present in a string as its integer value.
Return Value of charAt() in Java
Return Type : Character
The output that can be obtained after executing the method charAt() in Java is the index value of that particular character which is present in the string.
This is the specified index of that character given by the index parameter which is passed as part of the syntax of charAt() in Java.
NOTE: We can pass either a postive or negative integer based on which we shall expect the output.
The output for positive integer passed while executing the charAt() in Java is the character value if the index is in the range of the length of the string. If not then we will get an StringIndexOutOfBoundsException exception.
The output for negative integer passed while executing the charAt() in java gives the StringIndexOutOfBoundsException exception as well.
Exceptions of charAt() in Java
When we talk about exceptions that we might come across while working with the method charAt() in java we see that we might face one major exception too.
Yes, we are talking about the StringIndexOutOfBoundsException exception just as can be seen from below:
We see this StringIndexOutOfBoundsException exception on two scenarios:
- When we pass the int value while executing the method charAt() in java as more than the charcters present in the string, this exception will popup.
- Also, when we pass the int value while executing the method charAt() in java for a negative index we will still get this StringIndexOutOfBoundsException exception indicating that this method in java is out of bound for the index mentioned.
Example of charAt() in Java
Let us understand one basic example to explain the method charAt() in java.
Code:
Output:
Explanation: As can be seen from above we have printed the first and nineteenth character from the string which says "Learning Java" . Here as the total length of the character in the string is 12 and we asked to print character 1 and 7 which fall in the range we are seeing the correct output as assumed. Also, we know that in java the index of strings starts from 0 and not 1 . Therefore when we use the chartAt(0) it gives output as L which is the first character.
Try yourself by giving the index value either more than the string has or try giving negative index to see the exception that we talked out.
What is charAt() in Java?
As we walk through the module, one basic question that comes up is — What is charAt() in Java?
To answer same we can define the charAt() function in java as the method by which we can return the character value for a particular index number belongs to a string while executing the charAt() method.
Simply, it is the method which returns the character that is present in the string specified by its index. As we are know while counting the index numbers in java we start by 0 for specifying the first charcter, 1 for second character and so on.
This index value can be defined to be between 0 and (length of string-1). For a string which might include spaces, punctuation or special characters, the charAt() function in java will not throw any exception while counting that string and gives the output by including it that is, if for a index value which is given by a spaces, punctuation or special characters the charAt() counts include it as well. Note — we are bale to define for last character as well so this must be length of strng and not length of string -1
We must know that the charAt() in java throws StringIndexOutOfBoundsException when either we pass index number which is greater than the total index of the strings or if its a negative number ( index<0 or index>length() ).
Example of charAt() in Java
Example 1: Java String charAt() Method
Let us understand the charAt() Method by the below example.
Code:
Output:
Explanation:
Here we are using the charAt() in java to print the first , nineth and twelveth character of the string. As can be seen we used the charAt() in java and specified the index 0 , 8 and 11 respectively as the index value starts from 0 not 1 in java.
Example 2: Java String charAt — IndexOutOfBoundsException
Let us understand the charAt() Method to understand the IndexOutOfBoundsException by the below example.
Code:
Output:
Explanation:
Here we see that we get StringIndexOutOfBoundsException as the index that we gave was negative and as we already studied for any index which is negative of more than the range of the index for a string we will get this exception.
Example 3: Java String charAt — print all characters of string
Let us understand the charAt() Method to print all characters of the string with the help of below example.
Code:
Output:
Explanation:
Here we see that for printing all the characters of a string we have used the logic of loops in java. We used the for loop to print each index character from the index value ranging from 0 to lengthofstring()-1 . If we exceed beyond that it will definately give us out of bound exception.
Example 4: Java String charAt — Printing the first and last character of a string
Let us understand the charAt() Method to print the first and last character of a string with the help of below example.
Code:
Output:
Explanation:
Here we are using the charAt() method to print the first and last character of the string. As we already studied the index value in java starts from 0 and not 1 , we use dte index value as 0 to print the first character and length of string-1 to print the last character of the string.
Example 5: Java String charAt — Print Characters Presented at Odd Positions
Let us understand the charAt() Method to print the character present at the odd places of a string with the help of below example.
Code:
Output:
Explanation:
Here we have use the for loop along with charAt() in java to specify condition of index value to give output other than 0 which states that those are odd position and then once we have those index values we then print the values of those characters from the string.
Try yourself by modifying the code to print the characters present on the even position.
Example 6: Java String charAt — Counting the Number of Vowels in a String
Let us understand the charAt() Method to Count Counting the Number of Vowels in a String with the help of below example.
Code:
Output:
Explanation: Here we have made the use of charAt() in java to count the number of vowels in a string.
Example 6: Java String charAt — Counting the Occurrence
Let us understand the charAt() Method to Count Occurrence of a character from a string with the help of below example.
Code:
Output:
Explanation:
Here we have counted the occurance of the character 'S' form the string. We have used the for loop with charAt() in java to increase the counter value every time it sees the character 'S' and as shown in code above we have counted the number of timesthe letter 'S' occured in the string which in this case was 1.
Conclusion
- The method charAt() in java can be defined as the inbuilt method that returns the character value at the stated index number when searched in a string.
- The syntax of the charAt() in java is as follow:
The output for negative integer or out of bounds positive integer when passed while executing the charAt() in java gives the StringIndexOutOfBoundsException exception.
We have studied so many example covering variety of scenarios where we can make the use of simple charAt() in java and simplify our process.