Explanation
This Java code is designed to calculate the sum of the digits of an integer provided by the user. For instance, if the user enters 123, the program will calculate 1 + 2 + 3 and output 6.
The program begins by setting up a way to receive input from the user using the Scanner class. It prompts the user to "Enter a number:", reads that number, and stores it in an integer variable called num. Another integer variable, sum, is initialized to 0; this variable will accumulate the sum of the digits.
The core logic resides within a while loop. This loop continues to execute as long as the value of num is not zero. Inside the loop, two key operations occur:
sum += num % 10;: The modulo operator (%) gives the remainder of a division. Whennumis divided by10, the remainder is always its last digit (e.g.,123 % 10is3). This last digit is then added to thesumvariable.num = num / 10;: Integer division (/) discards any fractional part. Whennumis divided by10using integer division, its last digit is effectively removed (e.g.,123 / 10becomes12).
These two steps repeatedly extract the last digit, add it to the sum, and then remove it from the original number, until num eventually becomes 0. Once num is 0, it means all digits have been processed. The loop terminates, and the program prints the final calculated sum of digits to the console. Finally, it closes the Scanner object to release system resources.