Subodh Joshi
Subodh Joshi

Reputation: 13512

How and which one better approach for Java BigDecimal initialization?

I have to assign 0 to creditBalacne now here we can get two way

private BigDecimal creditBalance = new BigDecimal(0);

and other way

private BigDecimal creditBalance1 = BigDecimal.ZERO;

which one is better and why? and What way a developer to prefer ?

Upvotes: 0

Views: 125

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533750

The first option will create new objects (and later garbage)

If performance matters, the second option may be preferable. If in doubt, use the approach which is clearest and simplest to you.

BTW Another option is to use

private BugDecimal creditBalance1 = BigDecimal.valueOf(0);

This will use a cache of values where possible (and create new objects if not)

Upvotes: 1

Kayaman
Kayaman

Reputation: 73568

In the big scheme of things it doesn't matter which one you use. But since there already is a constant for zero, you might as well use it.

Upvotes: 1

Related Questions