Java Program to Add Two Numbers

This Java program adds two integers given in the program and displays the result on the screen.

To understand the topic, you need to have a basic understanding of two basic topics in Java.


Java Program for the Sum of two numbers

//Addition of two numbers
 
 public class AddTwoNumbers 
 {

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

     //Display result
     System.out.println("Sum of num1 and num2: "+sum);
   }
}

Output:

Sum of num1 and num2: 50


Java Program for the Sum of two numbers using Scanner

The Scanner class is used to get the inputs from the users in Java programming. We need to import a scanner class at the beginning.

import java.util.Scanner;
public class AddTwoNumbers
{
  public static void main(String[] args)
  {
    int num1, num2, sum;
    Scanner sc = new Scanner(System.in);

    //Taking Inputs from Users
    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:
5
Sum of these numbers: 15