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) { Scanner scanner = new Scanner(System.in); // Step 1: Get input number from the user System.out.print("Enter a non-negative integer: "); int number = scanner.nextInt(); // Step 2: Convert the integer to a string String numStr = String.valueOf(number); // Step 3: Initialize sum int sum = 0; // Step 4: Iterate through each character of the string for (int i = 0; i < numStr.length(); i++) { // Get the character at current index char digitChar = numStr.charAt(i); // Convert character to integer and add to sum sum += Character.getNumericValue(digitChar); } // Step 5: Print the result System.out.println("The sum of digits of " + number + " is: " + sum); scanner.close(); } }
Output
Clear
ADVERTISEMENTS