The program below separate digits in an integer using Java. It is the solution to Deitel’s Java How to Program (10th Edition) Chapter 2 Exercise 2.30.

Write an application that inputs one number consisting of five digits from the user, separates the number into its individual digits and prints the digits separated from one another by three spaces each. For example, if the user types in the number 42339, the program should print 4   2   3   3   9

Java program to separate digits in an Integer
Sample program run
NOTE: You can also use the %c format specifier to display blank space since display blank is a character. So the above statement can be displayed using
Note also that when you enter more than five digits, the program separate the digits and displays only the last five digits of the number entered. E.g.
Enter 1234567890 displays 6   7   8   9   0
Also, when you enter less than five digits, the program separate the digits in the integer and precedes the separated digits with zeros the number of digits required to make it five digits. E.g.
Enter 123 displays 0   0   1   2   3

Here is the same program to separate digits of a number written in C using another algorithm/method.


  1. Hello Druknar,
    The code worked fine but I agree that yours is better. There was no need calculating for the remainder before dividing to get the first digit of the number. The code has been updated. Thanks for your correction.

  2. Did you run the program? Because the code works fine. I just tried it. How come yours didn't work properly? What error are you getting?

    P.S. Your code worked too.

  3. First of all excuse my poor english.
    This program don't work properly, i think you should use:

Write A Comment