How do I get the last character of a string?

lonesarah picture lonesarah · Mar 2, 2011 · Viewed 556.9k times · Source

How do I get the last character of a string?

public class Main {
    public static void main(String[] args)  {
        String s = "test string";
        //char lastChar = ???
    }   
}

Answer

jcomeau_ictx picture jcomeau_ictx · Mar 2, 2011

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