This tutorial will discuss the method related to getting the string’s last character in Java.
How to Get the Last Character of a String in Java?
In Java, you can get the string’s last character using:
- substring() method
- charAt() method
We will now discuss each of the mentioned methods one by one!
Method 1: Getting Last Character of a String Using substring() Method
To get the string’s last character, you can use the Java “String” class “substring()” method. This method is primarily utilized to generate a substring by specifying the starting and ending indexes.
Syntax
The syntax for the substring() method is as:
Here, the substring() method takes two parameters as arguments: “startindex” and “endindex”.
We call this method to get the string’s last character as:
Here, “str.length() – 1” refers to the index of the last character of the string.
Example
We will create a String type variable named “str” and print its original value using the “System.out.println()” method:
System.out.println("Actual String: " + str);
Here, we will call the substring() method to get the last character of a string and save it in a String type variable named “lChar”. Lastly, we will print the resultant value on console:
System.out.println("Last word of the String is " + lChar);
The given output signifies that we have successfully retrieved the last character of the specified string:
Let’s head toward the second method.
Method 2: Getting Last Character of a String Using charAt() Method
Another method to get the string’s last character is the “charAt()” method. It is a predefined method that returns the character value from the string using its index.
Syntax
The syntax for the method charAt() is:
It accepts the “index” of the character that needs to be fetched from the given string.
We call this method to get the string’s last character as:
Here, “str.length() – 1” indicates the last index of the character.
Example
In this example, we will create a character type variable “lChar” to store the last character of the “str” String by calling the “charAt()” method and passing the index of the last character as an argument:
At last, print the last character with the help of the “System.out.println()” method:
Output
We have compiled all of the necessary instructions related to getting the string’s last character in Java.
Conclusion
For getting the string’s last character in Java, you can use two different methods: the substring() method and the charAt() method. The substring() method will return the character in the String type as a substring, while charAt() method will return the last character of a string in the character type. In this tutorial, we discussed the methods in detail for getting the string’s last character in Java.