Forums Register Login

New BigDecimal Vs BigDecimal.valueOf

+Pie Number of slices to send: Send
Hi All,

What is the difference between New BigDecimal and BigDecimal.valueOf. Which option better for used in coding. ?

+Pie Number of slices to send: Send
1
+Pie Number of slices to send: Send
Using new BigDecimal(...) will always create a new BigDecimal object. When you use BigDecimal.valueOf(...) then you might get a cached object (avoiding creating a new object), if it is more efficient.

So in general, it is better to use BigDecimal.valueOf(...) instead of new BigDecimal(...).

The same is valid for classes such as Integer, Double, etc.
+Pie Number of slices to send: Send
 

Jesper de Jong wrote:So in general, it is better to use BigDecimal.valueOf(...) instead of new BigDecimal(...).


This is actually true of all the standard classes that extend java.lang.Number (eg, java.lang.Integer, java.lang.Long ...etc), so it's not a bad general rule to follow.

In fact, I'd go even further and say that if a class (any class) provides a static valueOf() factory, you should use it in preference to new unless
(a) the documentation tells you otherwise.
(b) there is some overriding reason why you can't.

This is particularly true of BigDecimal. Try out the following:
System.out.println( new BigDecimal(0.1).toPlainString() );
System.out.println( BigDecimal.valueOf(0.1).toPlainString() );

and you'll see what I mean. And for an explanation why it does what it does, look at the documentation for new BigDecimal(double).

Winston
it's a teeny, tiny, wafer thin ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 10393 times.
Similar Threads
BigDecimal divide question
Just curious how ugly this is?
BigDecimal is driving me crazy
BigDecimal usage
BigDecimal() issue
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 07:49:32.