Add Two Numbers

Read two numbers from the user, add them, and display the result.

BeginnerTopic: Module 1: Basic Java Programs
Back

Java Add Two Numbers Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
import java.util.Scanner;

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

        System.out.print("Enter first number: ");
        double a = sc.nextDouble();

        System.out.print("Enter second number: ");
        double b = sc.nextDouble();

        double sum = a + b;
        System.out.println("Sum = " + sum);

        sc.close();
    }
}
Output
Enter first number: 10
Enter second number: 20
Sum = 30.0

Understanding Add Two Numbers

This program demonstrates:

Reading input from the keyboard using Scanner
Using double to handle decimal values
Performing addition and printing the result

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents