How do I get the last character of a string?

To get the last character of a string in Java, you can use the charAt() method of the String class, which returns the character at a specific index in the string.

To get the last character of a string, you can use the length of the string minus 1 as the index. For example:

String s = "Hello";
char last = s.charAt(s.length() - 1);
System.out.println(last);  // Outputs 'o'

This code gets the length of the string s using the length() method and then uses it to get the last character of the string using the charAt() method.

It is important to note that the charAt() method is zero-based, so the first character of the string has index 0, the second character has index 1, and so on. Therefore, to get the last character of the string, you need to use the index length() - 1.

You can also use the substring() method of the String class to get the last character of a string. To do this, you can use the following code:

String s = "Hello";
String last = s.substring(s.length() - 1);
System.out.println(last);  // Outputs "o"

This code gets a substring of the string s that consists of the last character of the string using the substring() method. The resulting last string will contain a single character.