How to retrieve the first character of a string in Java?

You can use the charAt() method with a string to access the first character. This method takes an integer as a parameter, which represents the index position of the character you want to retrieve. Since the index of a string starts at 0, you can pass in the parameter value of 0 to access the first character. Here is an example code for accessing the first character of a string:

String str = "Hello World";
char firstChar = str.charAt(0);
System.out.println(firstChar);

The output will be:

H
bannerAds