You can get the last character of a string in Java using the `substring()` method. Here’s an example:
Example:
public class LastCharacterExample {
public static void main(String[] args) {
String str = "Hello World!";
// Using substring() to get the last character
String lastChar = str.substring(str.length() - 1);
System.out.println("Last character: " + lastChar);
}
}
Explanation:
- `str.length() - 1` gives the index of the last character.
- `substring(str.length() - 1)` extracts the last character as a substring.
Output:
Last character: !