How to add two string numbers in Java

JavaObject Oriented ProgrammingProgramming

Strings are used to store a sequence of characters in Java, they are treated as objects. The String class of the java.lang package represents a String.

You can create a String either by using the new keyword (like any other object) or, by assigning value to the literal (like any other primitive datatype).

String stringObject = new String("Hello how are you"); String stringLiteral = "Welcome to Tutorialspoint";

Concatenating Strings

You can concatenate Strings in Java in the following ways −

Using the "+" operator − Java Provides a concatenation operator using this, you can directly add two String literals

Example

import java.util.Scanner; public class StringExample {    public static void main(String args[]) {       Scanner sc = new Scanner(System.in);       System.out.println("Enter the first string: ");       String str1 = sc.next();       System.out.println("Enter the second string: ");       String str2 = sc.next();       //Concatenating the two Strings       String result = str1+str2;       System.out.println(result);    } }

Output

Enter the first string: Krishna Enter the second string: Kasyap KrishnaKasyap Java

Using the concat() method − The concat() method of the String class accepts a String value, adds it to the current String and returns the concatenated value.

Example

import java.util.Scanner; public class StringExample {    public static void main(String args[]) {       Scanner sc = new Scanner(System.in);       System.out.println("Enter the first string: ");       String str1 = sc.next();       System.out.println("Enter the second string: ");       String str2 = sc.next();       //Concatenating the two Strings       String result = str1.concat(str2);       System.out.println(result);    } }

Output

Enter the first string: Krishna Enter the second string: Kasyap KrishnaKasyap

Using StringBuffer and StringBuilder classes − StringBuffer and StringBuilder classes are those that can be used as alternative to String when modification needed.

These are similar to String except they are mutable. These provide various methods for contents manipulation. The append() method of these classes accepts a String value and adds it to the current StringBuilder object.

Example

import java.util.Scanner; public class StringExample {    public static void main(String args[]) {       Scanner sc = new Scanner(System.in);       System.out.println("Enter the first string: ");       String str1 = sc.next();       System.out.println("Enter the second string: ");       String str2 = sc.next();       StringBuilder sb = new StringBuilder(str1);       //Concatenating the two Strings       sb.append(str2);       System.out.println(sb);    } }

Output

Enter the first string: Krishna Enter the second string: Kasyap KrishnaKasyap

How to add two string numbers in Java

Updated on 10-Oct-2019 08:20:46

Given two numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find sum of these two numbers.

Examples: 



Input : str1 = "3333311111111111", str2 = "44422222221111" Output : 3377733333332222 Input : str1 = "7777555511111111", str2 = "3332222221111" Output : 7780887733332222

The idea is based on school mathematics. We traverse both strings from end, one by one add digits and keep track of carry. To simplify the process, we do following: 1) Reverse both strings. 2) Keep adding digits one by one from 0’th index (in reversed strings) to end of smaller string, append the sum % 10 to end of result and keep track of carry as sum/10. 

3) Finally reverse the result. 

string findSum(string str1, string str2)

    if (str1.length() > str2.length())

    int n1 = str1.length(), n2 = str2.length();

    reverse(str1.begin(), str1.end());

    reverse(str2.begin(), str2.end());

        int sum = ((str1[i]-'0')+(str2[i]-'0')+carry);

        str.push_back(sum%10 + '0');

    for (int i=n1; i<n2; i++)

        int sum = ((str2[i]-'0')+carry);

        str.push_back(sum%10 + '0');

        str.push_back(carry+'0');

    reverse(str.begin(), str.end());

    cout << findSum(str1, str2);

static String findSum(String str1, String str2)

    if (str1.length() > str2.length()){

    int n1 = str1.length(), n2 = str2.length();

    str1=new StringBuilder(str1).reverse().toString();

    str2=new StringBuilder(str2).reverse().toString();

    for (int i = 0; i < n1; i++)

        int sum = ((int)(str1.charAt(i) - '0') +

                    (int)(str2.charAt(i) - '0') + carry);

        str += (char)(sum % 10 + '0');

    for (int i = n1; i < n2; i++)

        int sum = ((int)(str2.charAt(i) - '0') + carry);

        str += (char)(sum % 10 + '0');

        str += (char)(carry + '0');

    str = new StringBuilder(str).reverse().toString();

public static void main(String[] args)

    System.out.println(findSum(str1, str2));

    if (len(str1) > len(str2)):

        sum = ((ord(str1[i]) - 48) +

              ((ord(str2[i]) - 48) + carry));

        str += chr(sum % 10 + 48);

        sum = ((ord(str2[i]) - 48) + carry);

        str += chr(sum % 10 + 48);

print(findSum(str1, str2));

static string findSum(string str1, string str2)

    if (str1.Length > str2.Length){

    int n1 = str1.Length, n2 = str2.Length;

    char[] ch = str1.ToCharArray();

    char[] ch1 = str2.ToCharArray();

    str2 = new string( ch1 );

    for (int i = 0; i < n1; i++)

        int sum = ((int)(str1[i] - '0') +

                (int)(str2[i] - '0') + carry);

        str += (char)(sum % 10 + '0');

    for (int i = n1; i < n2; i++)

        int sum = ((int)(str2[i] - '0') + carry);

        str += (char)(sum % 10 + '0');

        str += (char)(carry + '0');

    char[] ch2 = str.ToCharArray();

    Console.WriteLine(findSum(str1, str2));

function findSum($str1, $str2)

    if (strlen($str1) > strlen($str2)) {

        $sum = ((ord($str1[$i])-48)+((ord($str2[$i])-48)+$carry));

    for ($i=$n1; $i<$n2; $i++)

        $sum = ((ord($str2[$i])-48)+$carry);

    echo findSum($str1, $str2);

function findSum(str1, str2)

    if (str1.length > str2.length)

    let n1 = str1.length, n2 = str2.length;

    str1 = str1.split("").reverse().join("");

    str2 = str2.split("").reverse().join("");

    for(let i = 0; i < n1; i++)

        let sum = ((str1[i].charCodeAt(0) -

                        '0'.charCodeAt(0)) + carry);

        str += String.fromCharCode(sum % 10 +

        carry = Math.floor(sum / 10);

    for(let i = n1; i < n2; i++)

        let sum = ((str2[i].charCodeAt(0) -

                        '0'.charCodeAt(0)) + carry);

        str += String.fromCharCode(sum % 10 +

        carry = Math.floor(sum / 10);

        str += String.fromCharCode(carry +

    str = str.split("").reverse().join("");

document.write(findSum(str1, str2))

Output: 

198123

Time Complexity: O(n1+n2) where n1 and n2 are lengths of two input strings representing numbers.

Auxiliary Space: O(max(n1, n2))

Optimization: 
We can avoid the first two string reverse operations by traversing them from the end. Below is the optimized solution. 

string findSum(string str1, string str2)

    if (str1.length() > str2.length())

    int n1 = str1.length(), n2 = str2.length();

    for (int i=n1-1; i>=0; i--)

        int sum = ((str1[i]-'0') +

        str.push_back(sum%10 + '0');

    for (int i=n2-n1-1; i>=0; i--)

        int sum = ((str2[i]-'0')+carry);

        str.push_back(sum%10 + '0');

        str.push_back(carry+'0');

    reverse(str.begin(), str.end());

    cout << findSum(str1, str2);

static String findSum(String str1, String str2)

    if (str1.length() > str2.length()){

    int n1 = str1.length(), n2 = str2.length();

    for (int i = n1 - 1; i>=0; i--)

        int sum = ((int)(str1.charAt(i)-'0') +

            (int)(str2.charAt(i+diff)-'0') + carry);

        str += (char)(sum % 10 + '0');

    for (int i = n2 - n1 - 1; i >= 0; i--)

        int sum = ((int)(str2.charAt(i) - '0') + carry);

        str += (char)(sum % 10 + '0');

        str += (char)(carry + '0');

    return new StringBuilder(str).reverse().toString();

public static void main(String[] args)

    System.out.println(findSum(str1, str2));

    for i in range(n1-1,-1,-1):

        sum = ((ord(str1[i])-ord('0')) +

                   int((ord(str2[i+diff])-ord('0'))) + carry)

    for i in range(n2-n1-1,-1,-1):

        sum = ((ord(str2[i])-ord('0'))+carry)

if __name__ == "__main__":

    print(findSum(str1, str2))

static string findSum(string str1, string str2)

    if (str1.Length > str2.Length)

    int n1 = str1.Length, n2 = str2.Length;

    for (int i = n1 - 1; i >= 0; i--)

        int sum = ((int)(str1[i] - '0') +

                (int)(str2[i + diff]-'0') + carry);

        str += (char)(sum % 10 + '0');

    for (int i = n2 - n1 - 1; i >= 0; i--)

        int sum = ((int)(str2[i] - '0') + carry);

        str += (char)(sum % 10 + '0');

        str += (char)(carry + '0');

    char[] ch2 = str.ToCharArray();

    Console.WriteLine(findSum(str1, str2));

function findSum($str1, $str2)

    if(strlen($str1)> strlen($str2))

    for ($i = $n1 - 1; $i >= 0; $i--)

        $sum = ((ord($str1[$i]) - ord('0')) +

               ((ord($str2[$i + $diff]) -

        $str3 .= chr($sum % 10 + ord('0'));

        $carry = (int)($sum / 10);

    for ($i = $n2 - $n1 - 1; $i >= 0; $i--)

        $sum = ((ord($str2[$i]) - ord('0')) + $carry);

        $str3 .= chr($sum % 10 + ord('0'));

        $carry = (int)($sum / 10);

        $str3 .= chr($carry + ord('0'));

print(findSum($str1, $str2));

function findSum(str1,str2)

    if (str1.length > str2.length){

    let n1 = str1.length, n2 = str2.length;

    for (let i=n1-1; i>=0; i--)

        let sum = ((str1.charCodeAt(i)-48) +

                (str2.charCodeAt(i+diff)-48) +

        carry = Math.floor(sum/10);

    for (let i=n2-n1-1; i>=0; i--)

        let sum = ((str2.charCodeAt(i)-48)+carry);

        carry = Math.floor(sum/10);

    str = str.split("").reverse().join("");

document.write(findSum(str1, str2),"</br>");

Output:

198123

Time Complexity: O(max(n1, n2)) where n1 and n2 are lengths of two input strings representing numbers.

Auxiliary Space: O(max(n1, n2))

This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


Practice Tags :