I have two string values using numbers. How to add(not concatenate) the two string values. Could you please help me.

my code:

string num='2016';
Output: 2016

string num1='2016'+'1';
Output: 20161

But I need 2017.Is it possible or not this way?

Integer num = Integer.valueOf('2006');
Integer num2 = Integer.valueOf('1');

Integer result = num + num2;

Update as per comment, to transform it to a String:

String str = String.valueOf(result);
  • i would however put that in a try/Catch block when you do that as you may throw a conversion error if the values are not formatted properly as numbers that you are trying to parse. – Ronnie Jan 18 '18 at 5:47
  • for brevity I have omitted try/catch – Santanu Boral Jan 18 '18 at 5:48
  • I understand - just thought i would comment it for other users to benefit as well. – Ronnie Jan 18 '18 at 5:51
  • @Santanu Boral, Thankyou for quick reply. The above scenario is working fine. But in the this way I am using string. The same output get using string or not? If possible could you please explain me – Preeth Jan 18 '18 at 5:54
  • you can get it to a string using String str = String.valueOf(result); System.debug(str); – Santanu Boral Jan 18 '18 at 5:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.