To get the first character of a string in Java, you can use the charAt
method of the String
class.
Here is an example:
String str = "abcdefg"; char firstChar = str.charAt(0);Source:www.lautturi.com
The charAt
method takes an index as an argument and returns the character at that index in the string. In this case, we pass 0 as the index, which returns the first character of the string (the character at index 0).
This will assign the value 'a' to the firstChar
variable.
Alternatively, you can use the substring
method to get the first character as a string, like this:
String str = "abcdefg"; String firstChar = str.substring(0, 1);
This will assign the value "a" to the firstChar
variable.