Search code examples
javavariablesvariable-assignment

one variable with multi assignments in java


double balance = loanAmount,principal,interest;

Can someone explain about this variable and multi assignments? How it is possible that "balance" can have 3 assignments (loanAmount, principal, and interest)?


Solution

  • This statement follows the form

    <type> <identifier> [ '=' <expression> ] [',' <identifier> [ '=' <expression> ] ...]
    

    So you're doing this:

    • Declare a variable of type double with the name balance and assign the value of loanAmount to it;
    • Declare a variable of type double with the name principal;
    • Declare a variable of type double with the name interest.

    See JLS § 14.4 for more details.

    I wouldn't advise this kind of declaration, but it is valid.