Reputation: 12621
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
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
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