In this code fragment, I can\'t sum a
and b
:
String a = \"10\";
String b = \"20\";
JOptionPane.showMessageDialog(null,a+b);
use BigInteger class to perform largely in length string addition operation.
BigInteger big = new BigInteger("77777777777777777777888888888888888888888888888856666666666666666666666666666666");
BigInteger big1 = new BigInteger("99999999999999995455555555555555556");
BigInteger big3 = big.add(big1);
Integer.parseInt() is used to convert String to Integer.In order to perform sum of two strings first strings need to be converted to Integers and then need to perform sum otherwise it just concatenates two strings instead of performing sum.
String a = "10"; String b = "20";
JOptionPane.showMessageDialog(null,Integer.parseInt(a)+Integer.parseInt(b));
Integer wrapper class has constructor which takes String parameter representing numbers.
String a= txtnum1.getText();//a="100"
String b= txtnum2.getText();//b="200"
Integer result;
int result_1;
String result_2;
try{
result = new Integer(a) + new Integer(b); // here variables a and b are Strings representing numbers. If not numbers, then new Integer(String) will throw number format exception.
int result_1=result.intValue();//convert to primitive datatype int if required.
result_2 = ""+result; //or result_2 = ""+result_1; both will work to convert in String format
}catch(NumberFormatException ex){
//if either a or b are Strings not representing numbers
result_2 = "Invalid input";
}