In this topic, we will learn to get the second last digit of a number with the help of examples.
There can be several ways to get second last digit; here we are discussing some solutions.
Table of Contents
Using modulo operator
Here, we are using modulo and divide operators to find the second last digit. The modulo operator gives remainder of a number while divide operator gives quotient as a result.
1 2 3 4 5 6 7 8 9 10 11 |
public class Main{ public static void main(String[] args){ int a = 120025; int secondLastDigit = (a % 100) / 10; System.out.println(secondLastDigit); secondLastDigit = (a / 10) % 10; System.out.println(secondLastDigit); } } |
Output
Using String’s chartAt() method
There is another example in which we can convert the number into a string and then using charAt()
method we get second last value after that result convert back to number using Character
class.
1 2 3 4 5 6 7 8 9 10 11 |
public class Main{ public static void main(String[] args){ int a = 120025; String number = Integer.toString(a); System.out.println(number); int secondLastDigit = Character.getNumericValue((number.charAt(number.length()-2))); System.out.println(secondLastDigit); } } |
Output
That’s all about how to return second last digit of given number.