Find the last character in a string in Java
In this tutorial, we will learn about how to find the last Character in String in Java.
Firstly, we should know about the Strings and the built-in methods used in Java.
String str = new String("CodeSpeedy");
There are different methods provided by Java in string here we will use charAt()
charAt() in Java
In Java String class charAt() returns a character at a specific index number in the string.
Number indexing starts from 0 to n-1 where n is the length of the string.
EXAMPLE
Input:
str = "CodeSpeedy" str.charAt(4); Output: S //return the character which is at 4th position in the string
Last Character in a string in Java using str.length() and str.charAt()
public class Strings {
public static void LastCharacter(String str)
{
int n = str.length();
char last = str.charAt(n - 1);
System.out.println("Last Character is : " + last);
}
// Driver Code
public static void main(String args[])
{
String str = "CodeSpeedy";
LastCharacter(str);
}
}Explanation
- Create a function LastCharacter and then find the string length by .length() method.
- Calculate the last character of the string and store it in char last.
- Printing the last character of the string.
- Then coming to the Driven code part give the String str in by literal method.
- Lastly, call the LastCharacter function.
OUTPUT

Leave a Reply