user1016403
user1016403

Reputation: 12621

Difference between BigDecimal.ONE and new BigDecimal("1")

what is the difference between below two lines of code?

BigDecimal one = new BigDecimal("1");
BigDecimal two = BigDecimal.ONE;

Are both the lines same?

Thanks!

Upvotes: 9

Views: 14567

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1502825

No, they're not quite the same - new BigDecimal("1") allocates a new object each time it's executed (and have to parse the value, too); BigDecimal.ONE will use a reference to the same existing object each time.

As BigDecimal is immutable, you can reuse an existing instance freely - so it makes sense to refer to a "pre-canned" object where you know what the value will be.

Upvotes: 20

Vandit Upadhyay
Vandit Upadhyay

Reputation: 345

BigDecimal.ONE is a pre scanned object and its efficient in terms of memory utilization as compared to

BigDecimal one = new BigDecimal("1"); 

because in this line it first creates an instance and then parses string "1" and then assigns.

whereas BigDecimal.ONE is like a constant and will give you direct value.

Hope this helps!

Upvotes: 7

Related Questions