Java program to find first and last digit of a number

In this article, we are going to find first and last digit of a number in Java.
To find first and last digit of any number, we can have several ways like using modulo operator or pow() and log() methods of Math class etc.

Let’s see some examples.
Before moving to example, let’s first create an algorithm to find first and last digit of a number.

Algorithm

Step 1: Take a number from the user.
Step 2: Create two variables firstDigit and lastDigit and initialize them by 0.
Step 3: Use modulo operator(%) to find last digit.
Step 4: Use either while loop and division operator (/) or log() and pow() methods of Math class to find

💻 Awesome Tech Resources:
  • Looking for ⚒️ tech jobs? Go to our job portal.
  • Looking for tech events? Go to tech events 🗓️ Calendar.️

.
Step 5: Display the result.

Using while loop

It is easy to use modulo operator that will return the last digit of the number, and we can use while loop and division operator to get first digit of number.

Output

Last digit: 7
First digit: 5

Using log() and pow() methods

If we want to use built-in methods like log() and pow() of Math class, then we can use log() method to get the number of digits and pow() method to get divisor value that later on used to get the first digit of number. See the example below.

Output

Last digit: 7
First digit: 5

Using while loop and pow() method

If we don’t want to use log() method then use while loop to count the number of digits and use that count into the pow() method to get divisor. See the example below.

Output:

Last digit: 7
First digit: 5

That’s all about Java program to find first and last digit of number in java.


import_contacts

You may also like:

Related Posts

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.