'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!



Solution 1:[1]

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.

Solution 2:[2]

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!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CodeFinity
Solution 2 M. Dudek