Java Program To Sum Of Two Number

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 programs takes both the numbers (entered by user) and prints the sum.

First Example: Sum of two numbers

  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);
 }
}
      
Output:
Sum of these numbers: 20

Second Example: Sum of two numbers using Scanner

    import java.util.Scanner;
 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: 
11
Enter Second Number: 
22
Sum of these numbers: 33
    

0 Comments