How do I get the last character of a string?
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 = ???
}
}
Solution 1:
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
Solution 2:
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
.