×

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to add it to the sum variable.

Example

Input: a23tr

Output: 5

Method 1

Algorithm

  1. Read String.
  2. Traverse the string till the end of the string using loops.
  3. Using the isDigit() method, we can check whether the character is a digit or not.
  4. If isDigit() will return true, then convert it into a number using parseInt().
  5. Add the digits to the sum variable.

Program

//Program to find the sum of digits in a string
import java. util.*;
import java.io.*;
public class Main
{ public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s=sc. next();
int sum=0;
for(int i=0;  i<  s. length() ;i++)
{
    char c=s. charAt(i);
    if(Character. isDigit(c))
    {
        int a=Integer.parseInt(String. valueOf(c));
        System.out.println("Numbers in the string are "+c);
        sum=sum+a;
    }//if
}// for loop
System.out.println("sum of digits in string is "+ sum);
}// main
}// class

Output

Sum of digits in string in java

Explanation

This program needs to read the string input using the Scanner class. In order to use the Scanner class, we need to import the util package. After reading the input, we need to traverse through the string, and if there are any digits in the string, we will find them by the isDigit() method, which returns true if it is a number and false if it is not. Then, we will convert the character to a string and add it to the sum variable.

Method 2

Program

import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
String s=sc.next();
int sum=0;
for (int i = 0; i < s.length(); i++) {
      if(Character.isDigit(s.charAt(i))) 
      sum=sum+Character.getNumericValue(s.charAt(i));
      }
   System.out.println("Sum of all the digit present in String : "+sum);
}
}

Output

Sum of digits in string in java

Explanation

In this method, we will use the getNumericValue() method to change the character to an integer. The integer value is added to the sum variable.

Method 3

Program

import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
String s=sc.next();
int sum=0;
        for(int i=0;i<s.length();i++)
        { 
            if(s.charAt(i)>='0' && s.charAt(i)<='9')
            {
                sum+=(s.charAt(i)-'0');
            }
        }
   System.out.println("Sum of all the digit present in String : "+sum);
}
}

Output:

Sum of digits in string in java

Explanation

In this method, we will subtract the character at the ith position with zero to type and convert it into an integer.


Related Topics

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

How to convert String to String array in Java

A String in Java is a thing that indicates a collection of letters. We must include the String class from java.lang package if we want to be using strings. An...

5 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Java Math sqrt() Method

The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value. Syntax: public static double sqrt(double a) Parameters: The parameter ‘a’ represents the number whose square...

2 minutes read.

Compare Two Times in Java

Definition The compareTo() function of the LocalTime class is used to compare times. The class's compareTo() method compares two LocalTime objects. Here we have two objects that have to be compared: the...

4 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Java Null Keyword

Null is a term that is only used for literal values in Java. Although it appears to be a term, it is a literal opposite of true and false. Java's...

3 minutes read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

String Manipulation in Java

String Manipulation in Java In Java, string manipulation is a common task performed by programmer. Java String class provides many built-in functions that are used to manipulate string. The manipulation of...

4 minutes read.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.