aspose file tools
The moose likes Java in General and the fly likes New BigDecimal Vs BigDecimal.valueOf Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Software Craftsman this week in the Agile forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "New BigDecimal Vs BigDecimal.valueOf" Watch "New BigDecimal Vs BigDecimal.valueOf" New topic

New BigDecimal Vs BigDecimal.valueOf

Nishan Patel
Ranch Hand

Joined: Sep 07, 2008
Posts: 689

Hi All,

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

Thanks, Nishan Patel
SCJP 1.5, SCWCD 1.5, OCPJWSD Java Developer,My Blog
John Jai

Joined: May 31, 2011
Posts: 1776
Might help -
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14667

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Winston Gutkowski

Joined: Mar 17, 2011
Posts: 8626

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).


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Have you tried LearnNowOnline?
subject: New BigDecimal Vs BigDecimal.valueOf