Find the second last digit of a number in Java

Find the second last digit of a number in Java

 

To find the second last digit of a number in Java, you can utilize simple arithmetic operations. The process involves using division and the modulo operator to isolate the desired digit.

Program to find second last digit of a number in Java

 

public class SecondLastDigit {
    public static void main(String[] args) {
        int number = 12345; // Example number
        int secondLastDigit = findSecondLastDigit(number);
        System.out.println("The second last digit is: " + secondLastDigit);
    }

    public static int findSecondLastDigit(int number) {
        return Math.abs((number / 10) % 10);
    }
}

Description

 

The goal is to extract the second last digit from a given integer. This can be achieved by following these steps:

  1. Input the Number: Start by obtaining the integer from which you want to find the second last digit.
  2. Remove the Last Digit: Use integer division by 10 (number / 10). This operation effectively removes the last digit of the number.
  3. Extract the Second Last Digit: Apply the modulo operator with 10 on the result from the previous step ((number / 10) % 10). This will give you the second last digit.
  4. Handle Negative Numbers: To ensure the result is always positive, you can use Math.abs() on the final result.

Output:-

 

The output of the provided Java code, which finds the second last digit of a number, will depend on the value assigned to the number variable.For the example given in the code:

int number = 12345; 

When you run the program, it will output:

The second last digit is: 4

Explanation:

  • The number 12345 has the digits: 1 (ten-thousands), 2 (thousands), 3 (hundreds), 4 (tens), and 5 (units).
  • The second last digit (the digit in the tens place) is 4, which is correctly identified by the method implemented in the code.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top