Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between BigDecimal.ONE and new BigDecimal("1")

Tags:

java

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!

like image 612
user1016403 Avatar asked Mar 30 '12 11:03

user1016403


People also ask

What is the difference between New BigDecimal and BigDecimal valueOf?

valueOf() has the more intuitive behaviour, while new BigDecimal(d) has the more correct one. Try both and see the difference.

What is new BigDecimal in Java?

A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point.

What is the value of BigDecimal one?

Field. static BigDecimal ONE − The value 1, with a scale of 0. static int ROUND_CEILING − Rounding mode to round towards positive infinity.

How do you know if two BigDecimal values are equal?

equals() method checks for equality of a BigDecimal value with the object passed. This method considers two BigDecimal objects equal if only if they are equal in value and scale.


1 Answers

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.

like image 158
Jon Skeet Avatar answered Nov 15 '22 22:11

Jon Skeet