sum the digits of a number java code example

Example 1: to get sum of even digits java

//To find the sum of even digits in a given Number

    public static int getEvenDigitSum(int number){
        if(number<0){
            return -1;
        }
        int finalNumber=0;
        while(number>0){
           if((number%10)%2==0){
               finalNumber+=number%10;

           }
           number=number/10; //takes out last digit to test the next digit


        }
        return finalNumber;
    }
//Output: ex:number=12323 -- Ans: 4

Example 2: sum of digits in java

import java.io.*;
public class sd
{
  public static void main(String [] args)throws IOException
  {
     InputStreamReader hi = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(hi);
        System.out.println("Enter the number");
        int num=Integer.parseInt(in.readLine());
    int sum=0;
    while(num>=0)
    {
      int rem=n;
      sum+=rem;
      int quo=n/10;
      n=quo;
    }
    System.out.println(sum);
  }
}

Tags:

Java Example