How to Add Two Numbers in Java – Step by Step Guide

Adding two numbers is one of the most basic programs in Java. This guide explains it in a professional way in English, with small Hinglish tips for easier understanding.

import java.util.Scanner;  // Import Scanner class to read user input

public class AddTwoNumbers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);  // Create Scanner object

        // Step 1: Prompt the user to enter the first number
        System.out.print("Enter first number: ");
        int num1 = sc.nextInt();  // Read first number

        // Step 2: Prompt the user to enter the second number
        System.out.print("Enter second number: ");
        int num2 = sc.nextInt();  // Read second number

        // Step 3: Add the two numbers
        int sum = num1 + num2;

        // Step 4: Display the sum
        System.out.println("The sum is: " + sum);
    }
}

Program Explanation

  1. Import the Scanner class to take input from the user.
    Scanner class import karein input lene ke liye.
  2. Create a Scanner object to read numbers.
    Scanner ka object (`sc`) create karein numbers read karne ke liye.
  3. Prompt the user to enter the first number and store it in `num1`.
    User se pehla number maangkar `num1` me store karein.
  4. Prompt the user to enter the second number and store it in `num2`.
    User se dusra number maangkar `num2` me store karein.
  5. Add the two numbers using the `+` operator and store the result in `sum`.
    Dono numbers ko `+` se add karke `sum` me store karein.
  6. Display the sum on the screen.
    Sum ko screen par print karein.

Example Run

Enter first number: 15
Enter second number: 25
The sum is: 40

Algorithm – Step by Step

  1. Start the program.
    Program start karein.
  2. Prompt the user to enter the first number and store it.
    User se pehla number maangkar store karein.
  3. Prompt the user to enter the second number and store it.
    User se dusra number maangkar store karein.
  4. Add the two numbers using the `+` operator.
    Dono numbers ko `+` se add karein.
  5. Display the sum on the screen.
    Sum ko screen par dikhaayein.
  6. End the program.
    Program ko end karein.

Flowchart

   ┌───────────┐
   │   Start   │
   │ Program start│
   └─────┬─────┘
         │
         ▼
 ┌─────────────────┐
 │ Input num1      │
 │ Pehla number lo │
 └─────┬───────────┘
       │
       ▼
 ┌─────────────────┐
 │ Input num2      │
 │ Dusra number lo │
 └─────┬───────────┘
       │
       ▼
 ┌───────────────────────┐
 │ sum = num1 + num2     │
 │ Dono numbers add karein│
 └─────┬─────────────────┘
       │
       ▼
 ┌───────────────────────┐
 │ Print sum             │
 │ Sum screen par dikhaayein│
 └─────┬─────────────────┘
       │
       ▼
   ┌───────────┐
   │   End     │
   │ Program end│
   └───────────┘