go to previous page   go to home page   go to next page highlighting

Answer:

Result: 55


negate() and immutable

negate() creates a new object, the negative of an existing BigInteger.


BigInteger value = new BigInteger( "38412946784" );
System.out.println( "Original: " + value );

value = value.negate();  // this creates a new object 
                         // and puts its reference in value
System.out.println( "New: " + value );

BigIntegers are immutable. You can't change the sign (or otherwise alter) a BigInteger object. The above code starts with value pointing to a BigInteger object. That object's negate() methods runs, creating a new object. A reference to that object is placed in value. The original object becomes garbage.

The program prints:

Original: 38412946784
New: -38412946784

Warning: often people misleadingly say that the first object has been converted to a negative. But in fact, a totally new object is created.


QUESTION 9:

What is printed by the following?

BigInteger value = new BigInteger( "50" );
value = value.negate().negate(); 
System.out.println( "New: " + value );

How many objects are created by the three lines of code?

How many reference variables are there in this code?


go to previous page   go to home page   go to next page