How to get the nth character of a string in Java
In this tutorial, we will learn how to get the nth character of a string in Java.
In Java, strings are the sequence of characters, where the index of the first character is 0
, the second character is 1
etc.
Getting the nth character
To access the nth character of a string, we can use the built-in charAt()
method in Java.
The charAt()
method takes the character index as an argument and return its value in the string.
Here is an example, that gets the first character B
from the following string:
String country = "Brazil";
char firstChar = country.charAt(0);
System.out.println(firstChar);
Output:
"B"
We can access the second and thrid characters of a string like this:
string secondChar = country.charAt(1); // r
string thirdChar = country.charAt(2); // a