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
Getting the nth character
To access the nth character of a string, we can use the built-in
charAt() method in Java.
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);
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