In this tutorial, you will learn how to get the last character of a String in Java. To achieve this, you will leverage the substring() and charAt() methods of the String class.

These are the two common approaches you can use to get the last character of a String in Java.

Using the substring() method

The substring() method returns a String from within another String. Let’s look at an example.

package com.javawhizz;
public class Main {
    public static void main(String[] args) {
        String description = "Java In Action";

        System.out.println(description
                .substring(description
                        .length() - 1));

    }
}

The method expects one parameter for the start index. As a result, the method will return the string starting from the specified index up to the end of the String.

Note that the starting index is inclusive. This means that the character at the starting index will also be a part of the sub-string.

To get the last character, pass length() - 1 as the argument of the method. Generally, the length() method returns the length of the String. As a result, reducing the length by 1 will return the index of the last character.

With this in place, the substring() method will return the character at the last index of the String.

Output

n

Using the charAt() method

The charAt() method is almost the same as the substring() method. The only difference is that it returns a character while the latter returns a String. Let’s look at an example.

package com.javawhizz;
public class Main {
    public static void main(String[] args) {
        String description = "Java In Action";

        System.out.println(description
              .charAt(description.length() - 1));

    }
}

The arguments for the method are the same as the one you used in the previous example.

To give you a brief explanation, the last character in the String is at the index 13. Since the length() of the String will return 14, reducing the value by 1 will give you the index of the last character.

As a result, the charAt() method will return the character at the last index of the String.

Output

n

Conclusion

In this tutorial, you have learned how to get the last character of a String in Java. The two ways covered include using the substring() and charAt() methods of the String class.

Go to the blog for more articles.

Happy Hacking!


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *