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);

ty

membersound
  • 74,158
  • 163
  • 522
  • 986

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
  • 464,258
  • 100
  • 912
  • 987
  • 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,502
  • 1
  • 22
  • 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,622
  • 3
  • 27
  • 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