java – How do I get the last character of a string?

java – How do I get the last character of a string?

The code:

public class Test {
    public static void main(String args[]) {
        String string = args[0];
        System.out.println(last character:  +
                           string.substring(string.length() - 1)); 
    }
}

The output of java Test abcdef:

last character: f

Here is a method using String.charAt():

String str = India;
System.out.println(last char =  + str.charAt(str.length() - 1));

The resulting output is last char = a.

java – How do I get the last character of a string?

The other answers are very complete, and you should definitely use them if youre trying to find the last character of a string. But if youre just trying to use a conditional (e.g. is the last character g), you could also do the following:

if (str.endsWith(g)) {

or, strings

if (str.endsWith(bar)) {

Leave a Reply

Your email address will not be published.