Java: Extract the first digit from an integer

Java Method: Exercise-20 with Solution

Write a Java method for extracting the first digit from a positive or negative integer.

Pictorial Presentation:

Java Method Exercises: Extract the first digit from an integer

Sample data:
(1234) ->1
(-2345) ->2

Sample Solution:

Java Code:

import java.util.Scanner;
public class Main { 
 public static void main(String[] args)
        Scanner in = new Scanner(System.in);
        System.out.print("Input an integer(positive/negative):");
        int n = in.nextInt();
        System.out.print("Extract the first digit from the said integer:\n");

public static int test(int n){
       int fact_num = 10;
       while(n / fact_num != 0){
        fact_num *= 10;
    return Math.abs(n / (fact_num/10));

Sample Output:

Input an integer(positive/negative): 1234
Extract the first digit from the said integer:

Flowchart :

Flowchart: Extract the first digit from an integer

Java Code Editor:

Contribute your code and comments through Disqus.

Previous Java Exercise: Accept three integers and return the middle one.
Next Java Exercise: Display the factors of 3 in a given integer

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day


Removes elements in an array until the passed function returns true. Returns the remaining elements in the array.

Loop through the array, using Arrays.copyOfRange() to drop the first element of the array until the returned value from the function is true. Returns the remaining elements.

public static int[] dropElements(int[] elements, IntPredicate condition) {
    while (elements.length > 0 && !condition.test(elements[0])) {
        elements = Arrays.copyOfRange(elements, 1, elements.length);
    return elements;

Ref: https://bit.ly/37YWqzD


We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook