Java ProgramsControl FlowFind First Digit

Find First Digit in Java

beginner·  Control Flow  ·  Loops

Problem

The first digit of a number is whatever remains once every digit after it has been divided away — dividing by 10 repeatedly strips digits from the right until only the leading one is left.

Given a number, find its first (leftmost) digit.

Input
45678
Output
First digit: 4

Java Program

Java
public class FirstDigit { public static void main(String[] args) { int n = 45678; while (n >= 10) { // keep dividing until only one digit remains n /= 10; } System.out.println("First digit: " + n); } }

Output

First digit: 4

Core Logic

Dividing the number by 10 for as long as it's 10 or greater strips away every digit except the leading one, since a single-digit value can't be divided down any further without losing it.

How It Works
  1. 1The loop condition n >= 10 keeps dividing as long as more than one digit remains.
  2. 2Each pass divides n by 10, discarding the last digit.
  3. 3Once n drops below 10, only the original first digit is left.
For 45678, dividing by 10 four times strips off 8, 7, 6, and 5 in turn, leaving 4.
💡

Key Point: The loop stops at n < 10 rather than n > 0 — dividing all the way down to zero would lose the first digit instead of isolating it.

Complexity
Time Complexity: O(d)Space Complexity: O(1)

Why: The loop strips one trailing digit per iteration until only the leading digit of the original d-digit number remains.

Key Concepts

while loopinteger division

Approach 2: Using String charAt(0)

Java
public class FirstDigitCharAt { public static void main(String[] args) { int n = 45678; // Reads the first character of the digit string and converts it back to a digit int firstDigit = String.valueOf(n).charAt(0) - '0'; System.out.println("First digit: " + firstDigit); } }

Output

First digit: 4

Core Logic

Converting the number to a String and reading its first character gives the leading digit directly, without a manual division loop.

How It Works
  1. 1String.valueOf(n) converts the number into its digit string.
  2. 2.charAt(0) reads the first character of that string, which is the leading digit.
  3. 3- '0' converts that character back into its numeric digit value.
For 45678, String.valueOf(45678).charAt(0) is '4', and subtracting '0' gives the numeric digit 4.
💡

Key Point: Building the digit string still costs work proportional to the digit count, even though only the first character ends up being read.

Complexity
Time Complexity: O(d)Space Complexity: O(d)

Why: Converting the number to a String still does work proportional to its digit count d, even though only the first character is read afterward.

Key Concepts

String.valueOf()charAt()

Related Programs