Search code examples
javajunitbigdecimal

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


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.


Solution

  • 👉🏼 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]