Write a program to get the character at the given index within the String
This program demonstrates how to retrieve a character from a string at a particular index using the charAt() method in Java.
- The program starts with the declaration of the Char_Index class.
- The main method is defined inside the class, which is the entry point of the program. Inside the main method, a string variable str is defined with the value "Tutor Joes".
- The charAt() method is then called on the string object str to retrieve the character at position 0, which is assigned to the integer variable a. Similarly, the character at position 6 is assigned to the integer variable b.
- The System.out.println() method is used to print the character at position 0 and 6 respectively. To display the character value instead of its ASCII value, the integer value is casted to char using (char).
Source Code
public class Char_Index
{
public static void main(String[] args)
{
String str = "Tutor Joes";
System.out.println("Given String : " + str);
int a = str.charAt(0);
int b = str.charAt(6);
System.out.println("The Character at Position 0 is " +(char)a);
System.out.println("The Character at Position 6 is " +(char)b);
}
}
Output
Given String : Tutor Joes
The Character at Position 0 is T
The Character at Position 6 is J