SwadhyAI Notes

All Java notes

How to Add Two Numbers in Java

The Challenge

Learn how to add two numbers in Java - the foundation of all mathematical operations!

Solution

Method 1: Using + Operator

java
public class Main {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 20;
        int sum = num1 + num2;
        System.out.println("Sum: " + sum); // Output: Sum: 30
    }
}

How It Works

  1. Declare two integer variables num1 and num2
  2. Use the + operator to add them together
  3. Store the result in a new variable sum
  4. Print the result using System.out.println()

Different Data Types

Adding Doubles

java
double num1 = 10.5;
double num2 = 20.3;
double sum = num1 + num2;
System.out.println("Sum: " + sum); // Output: Sum: 30.8

Using Scanner for User Input

java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter first number: ");
        int num1 = scanner.nextInt();
        
        System.out.print("Enter second number: ");
        int num2 = scanner.nextInt();
        
        int sum = num1 + num2;
        System.out.println("Sum: " + sum);
        
        scanner.close();
    }
}

Did You Know?

Java automatically handles integer overflow! If the sum exceeds the maximum value for an int (2,147,483,647), it wraps around to negative numbers. Use long for larger numbers!

Pro Tip

Use Math.addExact() to throw an exception on overflow instead of wrapping:

java
int sum = Math.addExact(num1, num2); // Throws ArithmeticException on overflow

Real-World Use Cases

  • Shopping Cart: Calculate total price of items
  • Banking: Add deposits to account balance
  • Gaming: Calculate total score from multiple rounds
  • Statistics: Sum data points for analysis
›Short versionOpen if you only have a minute.
  • int and long add with +. The result has the type of the operands after promotion.
  • Integer.MAX_VALUE + 1 wraps to Integer.MIN_VALUE. Math.addExact throws instead of wrapping.
  • "10" + "20" concatenates and produces "1020". Parse first if the values are text.
  • Money and other decimal totals do not belong in double. Use long cents or BigDecimal.

Add two numbers

Add two numeric values while choosing a type that matches the size and precision of the data.

Working approach

  • Use int for small whole numbers, long for larger counts, and BigDecimal when a decimal must be exact.
  • Name the inputs, compute once, then print or return that result.
  • Call Math.addExact when a wrapped total would be a bug rather than a defined answer.

Walk the sample

  1. Inputs 10 and 20
  2. Expression 10 + 20
  3. sum holds 30

The trap

The sample 10 + 20 hides overflow. A counter, a balance, or a product of two large ints wraps silently. String concatenation uses the same + token and does not add.

java
int wrapped = Integer.MAX_VALUE + 1;          // Integer.MIN_VALUE
int exact = Math.addExact(count, incoming);   // ArithmeticException if it will not fit
long wide = (long) left + right;              // promote before the sum grows past int

What does Integer.MAX_VALUE + 1 store in an int?

It stores -2147483648. Signed 32-bit addition wraps modulo 2^32.

Math.addExact(Integer.MAX_VALUE, 1) throws ArithmeticException, which is the behavior you want when a wrapped total would be stored as a balance or a size.

Time O(1), space O(1).

Easy to get wrong

  • Writing "10" + "20" and treating the result as thirty.
  • Ignoring overflow because the classroom inputs are small.