Jan 18, 2018 at 11:26 am Java

Simple Java Program to Find the First and Last Digit of a number

Here is a simple Java program to find the first and the last digit of a given number. Please note if you want the user to supply the number, you need to check for its validity. You also have to make sure the first character is not a minus sign. Otherwise, if the user supplies a negative number, the following line in the program will return the minus (-) sign instead of a number, which is what you expect.

String.valueOf(number).charAt(0)

 

here is the code


public class FirstLastDigit {
    public static void main(String[] args) {
	int number = 979870678;

	char firstDigit = String.valueOf(number).charAt(0);

        int lastDigit = number%10;

	System.out.println("Number given: " + number );
	System.out.println("First digit: " + firstDigit);
	System.out.println("Last digit: " + lastDigit );


	}
}

The output of this particular program is:
Number given: 979870678
First digit: 9
Last digit: 8

Leave a Reply

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