To get the second last index of a string in Java, you can use the `length()` method. The second last index of a string is:
Example:
public class SecondLastIndexExample { public static void main(String[] args) { String str = "Hello World!"; // Ensure string has at least two characters if (str.length() >= 2) { int secondLastIndex = str.length() - 2; char secondLastChar = str.charAt(secondLastIndex); System.out.println("Second last index: " + secondLastIndex); System.out.println("Second last character: " + secondLastChar); } else { System.out.println("String is too short!"); } } }
Explanation:
1. Check if the string has at least two characters (`str.length() >= 2`).
2. Calculate second last index using `str.length() – 2`.
3. Retrieve the second last character using `charAt(secondLastIndex)`.
4. Print the index and character.
Output:
Second last index: 10 Second last character: d