Java Program to Add two Numbers

Here we will see two programs to add two numbers, In the first program we specify the value of both the numbers in the program itself. The second program takes both the numbers (entered by the user) and prints the sum.

1st Example: Sum of two numbers

public class AddTwoNumbers {

   public static void main(String[] args) {
        
      int num1 = 20, num2 = 20, sum;
      sum = num1 + num2;

      System.out.println("Sum of these numbers: "+sum);
   }
}

Output:

Sum of these numbers: 40


Eclipse Code:




2nd Example: Sum of two numbers using Scanner

Note: The scanner allows us to capture the user input so that we can get the values of both the numbers from the user. The program then calculates the sum and displays it.

import java.util.Scanner;
public class AddTwoNumbers2 {

    public static void main(String[] args) {
        
        int num1, num2, sum;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter First Number: ");
        num1 = sc.nextInt();
        
        System.out.println("Enter Second Number: ");
        num2 = sc.nextInt();
        
        sc.close();
        sum = num1 + num2;
        System.out.println("Sum of these numbers: "+sum);
    }
}

Output:
Enter First Number: 
10
Enter Second Number: 
30
Sum of these numbers: 40


Eclipse Code:


Recommended topics:

1. Core Java Tutorial

2.  OOPs Concepts in detail

3. Java Programming




Previous
Next Post »

3 comments

Click here for comments
Anonymous
admin
8 August 2020 at 17:23 ×

Ohh thanx. Very helpful.

Reply
avatar
Unknown
admin
1 September 2020 at 17:09 ×

It's ace and content is very easy to make a sense .Great job

Reply
avatar
Unknown
admin
1 September 2020 at 17:10 ×

Nice content 👌👍

Reply
avatar