Java Program to find First Digit of a Number

Write a Java program to find First Digit of a Number with example.

Java Program to find First Digit of a Number Example 1

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

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

public class FirstDigit1 {
	private static Scanner sc;
	public static void main(String[] args) 
	{
		int number, first_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;
		}	
		
		System.out.println("\n The First Digit of a Given Number " + number + "  =  " + first_digit);
	}
}
Java Program to find First Digit of a Number 1

In this Java program to get first digit of a number program, Number = 5326

While Loop First Iteration while (5326 >= 10)
first_digit = first_digit / 10 = 5326 / 10 = 532

Second Iteration while (532 >= 10)
first_digit = 532 / 10 = 53

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

Fourth Iteration while (5 >= 10)
Condition is False. So, the Java compiler exit from the While Loop and prints 5 as output

Java Program to get First Digit of a Number Example 2

This program is the same as above. But this time, we are creating a separate Java method to find the First Digit of the user-entered value.

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

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

Java first digit in a number output

 Please Enter any Number that you wish : 2589

 The First Digit of a Given Number 2589  =  2