Java Online Compiler
Example: Sum of Digits using String Conversion in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sum of Digits using String Conversion import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { // Step 1: Create a Scanner object to read input Scanner scanner = new Scanner(System.in); // Step 2: Prompt the user to enter a number System.out.print("Enter a number: "); int number = scanner.nextInt(); // Step 3: Convert the integer to a string String numberStr = String.valueOf(number); // Step 4: Initialize sum to 0 int sum = 0; // Step 5: Iterate through each character of the string for (int i = 0; i < numberStr.length(); i++) { // Step 5a: Get the character at the current index char digitChar = numberStr.charAt(i); // Step 5b: Convert the character digit back to an integer and add to sum // Character.getNumericValue() handles conversion correctly for digits '0'-'9' sum += Character.getNumericValue(digitChar); } // Step 6: Print the sum of digits System.out.println("Sum of digits for " + number + " is: " + sum); // Step 7: Close the scanner scanner.close(); } }
Output
Clear
ADVERTISEMENTS