I have a
String id = "1";
String id2 = " 5";
How can i calculate
String sum = id + id2 + "2";
How can i sum it and give result = 8
I have a
String id = "1";
String id2 = " 5";
How can i calculate
String sum = id + id2 + "2";
How can i sum it and give result = 8
Unfortunately you don't have access to modify the String class and even if you did I do not believe you can override an operator in Java.
What you can do is create a static method:
public class StringUtils {
public static String ParseAdd(String... numStrings) {
int output = 0;
for (String numString : numStrings)
output += Integer.parseInt(numString);
return output + "";
}
then you can do:
String id = "1";
String id2 = " 5";
String sum = StringUtils.ParseAdd(id, id2, "2");
You will have to convert String into Integer before calculating sum, and again convert it back to String if you want output in String.
You can use Integer.parseInt(string) to convert String -> Integer.
After addition, you can use String.valueOf(integer) to convert Integer -> String.
String id = "01";
String id2 = "05";
int amount = Integer.parseInt(id) + Integer.parseInt(id2) + Integer.parseInt("2");
String sum = String.valueOf(amount);
Here is the relevant documentation, (Oracle). You need to call Integer.parseInt("num")
, to make your code work. It should look like this:
int sum = Integer.parseInt(id) + Integer.parseInt(id2) + Integer.parseInt("2");
Running an outputting its value using System.out.println()
, you get:
8
int sumInt = Integer.parseInt(id) + Integer.parseInt(id2) + Integer.parseInt("2");
String sum = String.vlaueOf(sumInt)
Here sum is "8" or whatever is need as per values of id and id2.