198

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 = ???
    }   
}
lonesarah
  • 2,823
  • 8
  • 21
  • 25
  • 2
    You've got several questions mixed up together. Broadly, yes, `str.charAt(str.length() - 1)` is usually the last character in the string; but consider what happens if str is empty, or null. – Vance Maverick Mar 02 '11 at 05:47
  • Its working fine. But logic of palidrome check is doesn't sound correct, please also mention what is the error you are getting. – Zimbabao Mar 02 '11 at 05:47
  • possible duplicate of [How to remove the last character from a string?](http://stackoverflow.com/questions/7438612/how-to-remove-the-last-character-from-a-string) – Nateowami Oct 04 '14 at 12:32

11 Answers11

261

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
jcomeau_ictx
  • 35,098
  • 6
  • 89
  • 99
  • 5
    returns it as a string, not a character, but you already know how to do the latter, and I'm not clear on what you're after. – jcomeau_ictx Mar 02 '11 at 05:46
  • 11
    What if your string is empty? – Danish Khan Jan 26 '15 at 19:19
  • 4
    it will raise an exception in that case. wouldn't you want it to? – jcomeau_ictx Jan 26 '15 at 19:33
  • 2
    Question asks for a character - this returns a one character long string. Should use `charAt()` not `substring()` – Andrew Mar 31 '20 at 13:19
  • 2
    Andrew, if you look back at the original question before it was edited, you'll see that the OP already tried charAt() and it wasn't what she wanted. That's one of the problems with a wiki-like medium such as SO, the questions are a moving target and sometimes the answers can look silly as a result. – jcomeau_ictx Mar 31 '20 at 19:13
  • @jcomeau_ictx is right. He left out exception handling because that is left up to the programmer (and the intended flow of the program). As such, any kind of error checking/handling here is superfluous. – Aquarelle Jun 30 '20 at 07:44
102

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.

Callum Luke Vernon
  • 215
  • 1
  • 3
  • 16
Aniket
  • 2,044
  • 4
  • 29
  • 48
  • 1
    be really careful if you are wanting to do a calculation on a number within a string as char values are quite different than a literal number and your math results will not work. – JesseBoyd Apr 09 '18 at 14:42
48

The other answers are very complete, and you should definitely use them if you're trying to find the last character of a string. But if you're 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")) {
Neil
  • 997
  • 9
  • 24
35

The other answers contain a lot of needless text and code. Here are two ways to get the last character of a String:

char

char lastChar = myString.charAt(myString.length() - 1);

String

String lastChar = myString.substring(myString.length() - 1);
Suragch
  • 364,799
  • 232
  • 1,155
  • 1,198
4

Try this:

if (s.charAt(0) == s.charAt(s.length() - 1))
hexacyanide
  • 76,426
  • 29
  • 148
  • 154
Bala R
  • 101,930
  • 22
  • 186
  • 204
2
public String lastChars(String a) {
if(a.length()>=1{
String str1 =a.substring(b.length()-1);
}
return str1;
}
  • I don't think this code will compile (only needs small fixes though), once you get it compile give it a test on an empty string to see if it works. – Knells Apr 05 '16 at 22:32
  • 2
    While this answer is probably correct and useful, it is preferred if you [include some explanation along with it](http://meta.stackexchange.com/q/114762/159034) to explain how it helps to solve the problem. This becomes especially useful in the future, if there is a change (possibly unrelated) that causes it to stop working and users need to understand how it once worked. Thanks! – Hatchet Apr 06 '16 at 00:18
2
public char LastChar(String a){
    return a.charAt(a.length() - 1);
}
2
String aString = "This will return the letter t";
System.out.println(aString.charAt(aString.length() - 1));

Output should be:

t

Happy coding!

2

Simple solution is:

public String frontBack(String str) {
  if (str == null || str.length() == 0) {
    return str;
  }
  char[] cs = str.toCharArray();
  char first = cs[0];
  cs[0] = cs[cs.length -1];
  cs[cs.length -1] = first;
  return new String(cs);
}

Using a character array (watch out for the nasty empty String or null String argument!)

Another solution uses StringBuilder (which is usually used to do String manupilation since String itself is immutable.

public String frontBack(String str) {
  if (str == null || str.length() == 0) {
    return str;
  }
  StringBuilder sb = new StringBuilder(str);  
  char first = sb.charAt(0);
  sb.setCharAt(0, sb.charAt(sb.length()-1));
  sb.setCharAt(sb.length()-1, first);
  return sb.toString();
}

Yet another approach (more for instruction than actual use) is this one:

public String frontBack(String str) {
  if (str == null || str.length() < 2) {
    return str;
  }
  StringBuilder sb = new StringBuilder(str);
  String sub = sb.substring(1, sb.length() -1);
  return sb.reverse().replace(1, sb.length() -1, sub).toString();
}

Here the complete string is reversed and then the part that should not be reversed is replaced with the substring. ;)

Yoko Zunna
  • 1,744
  • 12
  • 21
2

Here is a method I use to get the last xx of a string:

public static String takeLast(String value, int count) {
    if (value == null || value.trim().length() == 0) return "";
    if (count < 1) return "";

    if (value.length() > count) {
        return value.substring(value.length() - count);
    } else {
        return value;
    }
}

Then use it like so:

String testStr = "this is a test string";
String last1 = takeLast(testStr, 1); //Output: g
String last4 = takeLast(testStr, 4); //Output: ring
Pierre
  • 6,347
  • 4
  • 48
  • 67
1
 public char lastChar(String s) {
     if (s == "" || s == null)
        return ' ';
    char lc = s.charAt(s.length() - 1);
    return lc;
}
rakib
  • 21
  • 3