How Can I Create A BigDecimal Object that has null as it's value

107 views Asked by At

I have a java program that I am testing and a lot of the code is centered around the idea that a coin can have a value null. The issue, the coin is defined using Coin(BigDecimal) and I cannot figure out how to convert the Bug Decimal Part to represent null.

2

There are 2 answers

0
Basil Bourque On BEST ANSWER

Just assign null to your BigDecimal reference variable, as you would for any other class.

Example class defined as a record.

record Coin ( String name , BigDecimal monetaryValue ) {}

Usage with null.

record Coin( String name , BigDecimal monetaryValue ) { }
Coin c = new Coin ( "Mystery" , null );

c.toString() = Coin[name=Mystery, monetaryValue=null]

0
Nakip Ali On

You can define BigDecimal.ZERO your coin variable instead of defining null.

According to document

Docs Oracle

All methods and constructors for this class throw NullPointerException when passed a null object reference for any input parameter.