Java Program to find First and Last Digit of a Number

Write a Java Program to find First and Last Digit of a Number with example.

Java Program to return First and Last Digit of a Number Example 1

This program allows the user to enter any number. Next, this Java program returns the First and Last Digit of the user entered value.

// Java Program to find First and Last Digit of a Number
import java.util.Scanner;

public class FirstandLastDigit1 {
	private static Scanner sc;
	public static void main(String[] args) 
	{
		int number, first_digit, last_digit;
		sc = new Scanner(System.in);
		
		System.out.print(" Please Enter any Number that you wish : ");
		number = sc.nextInt();	
		
		first_digit = number;
		while(first_digit >= 10)
		{
			first_digit = first_digit / 10;
		}	
		
		last_digit = number % 10;
		
		System.out.println("\n The First Digit of a Given Number " + number + "  =  " + first_digit);
		System.out.println("\n The Last Digit of a Given Number " + number + "  =  " + last_digit);
	}
}
Java Program to find First and Last Digit of a Number 1

Number = 2356

While Loop First Iteration while (2356 >= 10)
first_digit = first_digit / 10 = 2356 / 10 = 235

Second Iteration while (235 >= 10)
first_digit = 235 / 10 = 23

Third Iteration while (23 >= 10)
first_digit = 23 / 10 = 5

Fourth Iteration while (5 >= 10)
Condition is False. So, the Java compiler exits from the While Loop
first_digit = 5

last_digit = 2356 % 10
last_digit = 6

Java Program to find First and Last Digit of a Number Example 2

This Java program is the same as the above first and last digit example. But in this program, we are creating two separate Java methods to find the First Digit and last Digit of the user-entered value. We have previously demonstrated in our earlier articles. So, Please refer First Digit and Last Digit article.

// Java Program to find First and Last Digit of a Number
import java.util.Scanner;

public class FirstandLastDigit2 {
	private static Scanner sc;
	public static void main(String[] args) 
	{
		int number, first_digit, last_digit;
		sc = new Scanner(System.in);
		
		System.out.print(" Please Enter any Number that you wish : ");
		number = sc.nextInt();	
		first_digit = firstDigit(number);
		
		last_digit = lastDigit(number);
		
		System.out.println("\n The First Digit of a Given Number " + number + "  =  " + first_digit);	
		System.out.println("\n The Last Digit of a Given Number " + number + "  =  " + last_digit);
	}
	
	public static int firstDigit(int num)
	{
		while(num >= 10)
		{
			num = num / 10;
		}	
		return num;	
	}
	
	public static int lastDigit(int num)
	{
		return num % 10;	
	}
}

Java First and Last Digit in a Number output

 Please Enter any Number that you wish : 789625

 The First Digit of a Given Number 789625  =  7

 The Last Digit of a Given Number 789625  =  5

Comments are closed.