2

Is it possible to do +- operations like this somehow?

BigInteger a = new BigInteger("1");
BigInteger b = new BigInteger("2");
BigInteger result;

a+=b;
//result = a.add(b);
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
membersound
  • 81,582
  • 193
  • 585
  • 1,120

3 Answers3

4

In a word, no. There is no operator overloading in Java, and BigInteger is not one of the special types for which there is compiler magic to support operators such as + and +=.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Again immutability is not a reason for not having language support for the arithmetic operators. `String` is also immutable and there is language support for the `+=` operator. E.g.: `String foo = "foo"; foo += "bar";` You're changing the reference `foo`, not the contents of the object it points to. – SimonC Feb 22 '12 at 14:48
3

Unfortunately not. Operator overloading is not supported in the Java language. The syntax only works for the other numeric primitive wrappers via auto-boxing, which wouldn't make sense for BigInteger as there's no equivalent primitive.

SimonC
  • 6,590
  • 1
  • 23
  • 40
0

Nope. BigIntegers are immutable, so you can't change the value of a after creating it. And the usual mathematical operators don't work on them either, so you can't do a += b either.

You'd need to do what you have commented-out there -- result = a.add(b);

Jim Kiley
  • 3,632
  • 3
  • 26
  • 43
  • 2
    Immutability is irrelevant to the question. Primitives are immutable too, but you can use the arithmetic operations with them. – SimonC Feb 22 '12 at 14:34