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
JavaRanch » Java Forums » Java » Java in General
Bookmark "New BigDecimal Vs BigDecimal.valueOf" Watch "New BigDecimal Vs BigDecimal.valueOf" New topic
Author

New BigDecimal Vs BigDecimal.valueOf

Nishan Patel
Ranch Hand

Joined: Sep 07, 2008
Posts: 688

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
Bartender

Joined: May 31, 2011
Posts: 1776
Might help - http://www.coderanch.com/t/560274/java/java/convert-BigDecimal-Double
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14160
    
  19

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 7 API documentation
Scala Notes - My blog about Scala
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7837
    
  21

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


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: New BigDecimal Vs BigDecimal.valueOf