How to Add to Numbers in Java Program ?

  Java Interview Q&A

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

1. Sum of two numbers in Java Program

public class AddTwoNumbers {

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

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

Result:

Sum of these numbers: 20

Sum of two numbers using Scanner

The scanner allows us to capture user input so that we can get the values of both 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);
    }
}

Result:

Enter First Number: 
121
Enter Second Number: 
19
Sum of these numbers: 140

LEAVE A COMMENT