Junior — Middle
What types of data are used to account for the balance on a bank account?
sobes.tech AI
Answer from AI
To account for the balance on a bank account in Java, the following data types are usually used:
- BigDecimal — the preferred type for storing monetary values, as it provides precision in floating-point operations and prevents rounding errors.
- long or int — sometimes used to store amounts in the smallest units of currency (for example, kopecks or cents) to avoid issues with floating-point.
Example of using BigDecimal:
import java.math.BigDecimal;
public class BankAccount {
private BigDecimal balance;
public BankAccount() {
this.balance = BigDecimal.ZERO;
}
public void deposit(BigDecimal amount) {
balance = balance.add(amount);
}
public void withdraw(BigDecimal amount) {
balance = balance.subtract(amount);
}
public BigDecimal getBalance() {
return balance;
}
}