user3234625
user3234625

Reputation: 1

BigDecimal bigDecimal = BigDecimal.ONE;

When you do something like this

BigDecimal bigDecimal = BigDecimal.ONE;

why does bigDecimal become a new object?

Upvotes: 0

Views: 508

Answers (3)

Thomas Mueller
Thomas Mueller

Reputation: 50127

In this case, the variable (or field) bigDecimal doesn't become a new object. It is only a reference to the object which is referenced by the existing static field java.math.BigDecimal.ONE.

The object itself (the one that represents 1) is created only once: when the class BigDecimal is loaded. For Java 7, this is done using new BigDecimal(BigInteger.ONE, 1, 0, 1).

The assignment you did is better than creating a new object yourself using = new BigDecimal(...), because the existing object is re-used.

Upvotes: 8

Henry
Henry

Reputation: 43788

No new object is allocated. bigDecimal refers to the same object as BigDecimal.ONE.

If you later do

bigDecimal = bigDecimal.add(BigDecimal.ONE);

a reference to another object (which has a value of 2) will be assigned to bigDecimal. After that statement bigDecimal and BigDecimal.ONE no longer point to the same object.

Upvotes: 1

venergiac
venergiac

Reputation: 7717

From Java Documentation

public static final BigDecimal ONE

The value 1, with a scale of 0.

Then ONE is static and is the same instance object on the same classloader context.

Upvotes: 0

Related Questions