• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

New BigDecimal Vs BigDecimal.valueOf

 
Nishan Patel
Ranch Hand
Posts: 689
Eclipse IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

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

 
John Jai
Rancher
Posts: 1776
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15354
39
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Winston Gutkowski
Bartender
Pie
Posts: 10422
63
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic