Back to Beginner: I/O, Arithmetic, Loops
Q17Question 17 of 30

Add Two Numbers: read A and B, print their sum

Key Concepts
  • Adding two numbers is read, add, print: the most basic arithmetic operation and the foundation of every financial calculation.
  • For money, use BigDecimal with the add method, not the plus operator on double, because binary floating point cannot represent paise exactly.
  • Construct BigDecimal from a String, not from a double, because new BigDecimal(0.1) captures the binary error while new BigDecimal("0.1") is exact.
  • BigDecimal addition never overflows because it has arbitrary precision, unlike int or long.
  • Set the result to a fixed scale with setScale(2, RoundingMode.HALF_EVEN) so the stored amount always has exactly two decimal places.
  • Validate inputs are non-null and non-negative for deposits before adding.

Definition

Adding two numbers is read, add, print, but in banking the amounts must be BigDecimal so the sum of money is exact to the paisa.
  • Addition – the most basic arithmetic operation: read two operands, apply +, output the sum.
  • BigDecimal for money – double cannot represent 0.10 exactly; BigDecimal stores values as an unscaled integer and a scale.
  • String constructor – new BigDecimal("0.1") is exact; new BigDecimal(0.1) captures binary error.
  • add method – a.add(b) returns a new BigDecimal; the + operator does not work on objects.
  • Fixed scale – setScale(2, RoundingMode.HALF_EVEN) ensures two decimal places for rupees and paise.

Rajesh deposits 4 thousand rupees in the morning and 7 thousand in the afternoon at National Bank of India. The teller adds the two amounts and credits eleven thousand to savings account SAV2001. That single addition, done with exact decimal arithmetic, is the whole operation.

Understanding the Concepts

What is the problem?

Read two numbers A and B, compute their sum, and print it. For input 4 and 7, the output is 11.

Why is double wrong for money?

Double stores values in IEEE 754 binary floating point. The decimal fraction 0.10 cannot be represented exactly, so 0.1 + 0.2 gives 0.30000000000000004. Over thousands of transactions this drift corrupts a bank statement.

JAVA
System.out.println(0.1 + 0.2); // 0.30000000000000004

How do you add money correctly with BigDecimal?

JAVA
package com.bank.service;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class DepositTotalService {

    public static BigDecimal addAmounts(BigDecimal a, BigDecimal b) {
        if (a == null || b == null) {
            throw new IllegalArgumentException("Amount must not be null");
        }
        return a.add(b).setScale(2, RoundingMode.HALF_EVEN);
    }

    public static void main(String[] args) {
        BigDecimal morning = new BigDecimal("4000.00");
        BigDecimal afternoon = new BigDecimal("7000.00");
        BigDecimal total = addAmounts(morning, afternoon);
        System.out.println("Total credited: " + total);
    }
}
TEXT
Total credited: 11000.00

Why construct BigDecimal from a String?

JAVA
// Wrong: captures binary floating-point error
new BigDecimal(0.1);
// 0.1000000000000000055511151231257827021181583404541015625

// Correct: exact decimal value
new BigDecimal("0.1");
// 0.1

What is the flowchart?

DIAGRAM
  Start → Read A → Read B → sum = A + B → Print sum → End

In Java with BigDecimal: sum = a.add(b).setScale(2, RoundingMode.HALF_EVEN).

What are edge cases?

  • Both zero: sum is zero.
  • One amount is zero: sum equals the other amount.
  • Very large amounts: BigDecimal handles them without overflow, unlike long.
  • Fractional paise: setScale rounds to two decimal places.

What are common mistakes?

JAVA
// Wrong: using + operator on BigDecimal
BigDecimal sum = a + b; // does not compile!

// Correct: use add method
BigDecimal sum = a.add(b);

// Wrong: not fixing scale
BigDecimal sum = a.add(b); // scale may vary

// Correct: fix scale for consistent storage
BigDecimal sum = a.add(b).setScale(2, RoundingMode.HALF_EVEN);

How is BigDecimal addition different from int addition?

| Feature | int / long | BigDecimal |
|---|---|---|
| Operator | + | .add() |
| Overflow | silently wraps | never (arbitrary precision) |
| Precision | exact for integers | exact for decimals |
| Paise handling | manual scaling | built-in scale |

What should a senior engineer know?

A senior engineer defines amount types and rounding modes as shared constants. Every monetary addition, subtraction, and division in the codebase uses the same conventions. Using HALF_EVEN (banker's rounding) reduces systematic bias when totals are computed across millions of accounts.

What are common interview follow-up questions?

  • What is the difference between HALF_UP and HALF_EVEN rounding?
  • How does BigDecimal store its value internally? (unscaled value and scale)
  • What happens if you call equals on two BigDecimal values with different scales?

Visual Overview

DIAGRAM
  ┌─────────┐
  │  Start  │
  └────┬────┘
       ▼
  ┌──────────────────────┐
  │  Read A (BigDecimal)  │
  └────┬─────────────────┘
       ▼
  ┌──────────────────────┐
  │  Read B (BigDecimal)  │
  └────┬─────────────────┘
       ▼
  ┌──────────────────────────────────┐
  │  sum = a.add(b).setScale(2, HE) │
  └────┬─────────────────────────────┘
       ▼
  ┌──────────────┐
  │  Print sum   │
  └────┬─────────┘
       ▼
  ┌─────────┐
  │   End   │
  └─────────┘

Key Takeaway

Adding two numbers is the simplest arithmetic operation: read A, read B, compute sum = A + B, and print. But the moment those numbers are money, the naive approach becomes a bug.

Floating-point types like double store numbers in binary, and common decimal amounts like ten paise cannot be represented exactly. Adding money as doubles slowly drifts, and a statement ends up a fraction wrong. In banking that is never acceptable, so every monetary amount is a BigDecimal, addition uses the add method, and the result is fixed to two decimal places with an explicit rounding mode.

Always construct BigDecimal from a String rather than a double so the value is captured exactly. And validate that inputs are present and non-negative before adding.

In a banking project at National Bank of India, Rajesh made two deposits into savings account SAV2001 on the same day. The DepositTotalService added the two BigDecimal amounts, validated them, and set the scale to two with HALF_EVEN rounding. Four thousand plus seven thousand totaled exactly eleven thousand with two decimal places.

Remember one sentence: for money, add with BigDecimal's add method and construct from Strings, because double cannot represent paise exactly.

---

Share
Use ← → arrow keys to navigate