Java 8 Program to Find the Sum of All Digits of a Number

1. Introduction

Calculating the sum of all digits in a number is a basic programming task that demonstrates the use of arithmetic operations and control structures. In this blog post, we will use Java 8 features to streamline the process of adding up the digits of a given number. This approach illustrates how Java 8's functional programming capabilities can simplify traditional tasks.

2. Program Steps

1. Import the necessary classes.

2. Read the number from the user.

3. Convert the number into a stream of characters (digits).

4. Convert each character back to a digit and sum them up.

5. Display the sum of the digits.

3. Code Program

import java.util.Scanner;

public class SumOfDigits {
    public static void main(String[] args) {
        // Creating a Scanner object to read input
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a number:");
        String number = scanner.nextLine();
        scanner.close(); // Closing the scanner

        // Calculating the sum of digits
        int sum = number.chars() // Creating an IntStream of chars (ASCII values)
                         .map(Character::getNumericValue) // Converting each ASCII value to its numeric value
                         .sum(); // Summing up the numeric values

        // Displaying the sum of the digits
        System.out.println("The sum of the digits is: " + sum);
    }
}

Output:

Enter a number:
12345
The sum of the digits is: 15

Explanation:

1. The program begins by importing the Scanner class to facilitate reading input from the user.

2. A Scanner object is created, and the user is prompted to enter a number. The input number is read as a String to easily process each digit.

3. The entered number (String) is then converted into a stream of characters. In Java, the chars() method of the String class creates an IntStream representing the sequence of characters in the String by their ASCII values.

4. Each character in the stream is mapped to its numeric value using the map operation and Character::getNumericValue, which converts the ASCII value of each digit character to the corresponding integer value (0-9).

5. The sum() operation is applied to the stream of numeric values to calculate the total sum of the digits.

6. Finally, the sum is printed to the console.

7. The Scanner object is closed to prevent resource leaks, adhering to best practices in Java programming.

Comments