Java String charAt() method explained
It is a predefined function which is present in the Java.lang.String package. It is used to find the specific character at the particular index of a string. It's return type is character, let's see it's implementation-
Syntax of charAt() method
public char charAt(int index) {}
here, the function charAt() takes the parameter of type integer to enter the specified index at which the character you want to find in a string and charAt() simply returns that character.
Example 01 of charAt() method
public class CharAt {
public static void main(String[] args) {
String s1 = "stephen";
char mychar = s1.charAt(2);
System.out.println(mychar);
}
}
Output:
e
here, the character stored at index 2 is 'e' so we have stored this character in our own variable mychar and output it simply.
Imp.note: the first value of string is stored at index 0 and second value at index 2 and so on for example- the string we have taken here in the first example is "stephen" in this string 's' is stored at index 0 and 't' is stored at index 1 and so on.
Example 02 of charAt() method
program 01: "To find the character at a particular index entered by the user of the string"
Problem Statement: "first, predefine the string in your code and ask for index number from the user and show the particular character stored at that index number which is entered by user, In case the user entered number less than zero or more than the length of a string show him/her invalid input and give another chance to re enter the number repeatedly till the user entered the valid index number and if the user enters the valid index number show character and terminate the code.
Source code:
import java.util.Scanner;
public class CharAt {
public static void main(String[] args) {
takeIndex();
}
public static void takeIndex()
{
Scanner sc = new Scanner(System.in);
String s1 = "stephen";
System.out.println("Enter the index number for which you want to find the character in a string");
int takeIndex = sc.nextInt();
if(takeIndex>s1.length() || takeIndex<0)
{
System.out.println("Invalid input");
System.out.println("enter again");
takeIndex();
}
else
{
System.out.println(s1.charAt(takeIndex));
}
}
}
Output:
Enter the index number for which you want to find the character in a string
-90
Invalid input
enter again
Enter the index number for which you want to find the character in a string
89
Invalid input
enter again
Enter the index number for which you want to find the character in a string
5
e
Hello, visitor your comments are so helpful for us so do not hesitate just write the comment we read all your comments so don't think your comment goes waste.