-2

I want to add two numbers in java:76561197960265728 and 96279315. I tried with Big Integer but it didn't work ;/ POC:

BigInteger big = new BigInteger("96279315");
BigInteger bigg = new BigInteger("76561197960265728");
bigg.add(big);
System.out.println(bigg);

In PHP i can do:

echo bcadd(96279315, '76561197960265728');

and it works well.

How to (easy) do it in java? Thanks

ajtamwojtek
  • 763
  • 6
  • 19
  • 4
    Please make SOME research effort before asking. Just searching `biginteger.add` or even `how to add biginteger in java` pulls up a [duplicate](http://stackoverflow.com/questions/1783912/java-how-to-use-biginteger), a [related question which is very nearly a duplicate](http://stackoverflow.com/questions/3748846/how-to-add-two-numbers-of-any-length-in-java), a nice [tutorial which shows you how to use it](http://www.tutorialspoint.com/java/math/biginteger_add.htm) and even [the documentation](http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#add(java.math.BigInteger)). – tnw Aug 18 '15 at 18:41

2 Answers2

4

The add method doesn't modify the object; it returns a new BigInteger representing the sum.

Assign the returned value back to bigg.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • I was bemused... Thanks :)) – ajtamwojtek Aug 18 '15 at 18:38
  • As the asker of this question, you may [accept exactly one answer](http://stackoverflow.com/help/someone-answers) by clicking the check mark next to the answer that you think is the best. – rgettman Aug 18 '15 at 18:44
1

BigInteger (and BigDecimal too) is unlike any other Numerical object in Java inmutable. This means that you cannot change that state of the object after it was created. This is adventagous for many reasons, but has a serious drawback:

You are getting new Objects after each operation, which you need assign: So instead of a simple:

a.add(b);

You need to do:

result = a.add(b);

Or if you can save a new variable declaration by reusing a:

a = a.add(b);
Gergely Bacso
  • 14,243
  • 2
  • 44
  • 64