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.
[toc]
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.
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
2
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.
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
2
That’s all about how to return second last digit of given number.