Find the second last digit of a number in Java
In this tutorial, we will be solving the problem of finding the second last digit of a number in Java.
We will use a simple trick to solve this problem efficiently.
There are various tricks you can apply when solving problem-solving related questions.
Steps to Solve the Problem
- Create a class named
check23
: Inside this class, we will take an integer variable. - Assign a value: For the time being, let’s assign a 6-digit value for checking.
- Get the last two digits: To get the last two digits, we will take the remainder when dividing the number by 100.
- Extract the second last digit: After getting the last two digits, we will divide the result by 10 to get the second last digit.
- Use Math.abs method: To ensure we get the value in an absolute manner, we will use the
Math.abs
method. This method ensures the value is positive, regardless of its sign. - Display the result: Finally, we will display the result using the
System.out.print
method.
public class check23 { public static void main(String[] args) { int i = 123456; System.out.print(Math.abs((i % 100) / 10)); } }
Define the class and main method:
public class check23 { public static void main(String[] args) {
Initialize the integer variable:
int i = 123456;
Calculate the second last digit:
System.out.print(Math.abs((i % 100) / 10));
Sample Output
After successfully compiling and running the above code, the output will be: 0
You can also find another solution the given problem here: https://www.codespeedy.com/java-program-to-find-second-last-digit-of-a-number/