Search code examples
javastring-parsing

Counting with strings (numbers)


I have a two strings containing a certain number (let's say it is not higher than 10).

String five = "5";
String two = "2";

How can I add them up together?

String seven = five + two;

Obviously does not work.

How can I add both numbers to each other and let the output be "7"? Do I have to convert the string first (to an int for example)?


Solution

  • This is not an Android question, this is Java question.

    try {
       String seven = Integer.toString(Integer.parseInt(five) + Integer.parseInt(two));
    } catch (NumberFormatException nfex) {
    // one of the strings was not a number
    }