Top 2 Methods of Addition of Two numbers in Java Program

Addition of Two numbers in Java

If you have started learning Java recently , then you must try Addition of Two numbers in Java Program as a basic program. Once you are done with the add two numbers programs you will be able to understand the basic understanding on how Java works.

In this Post we will see be going through the the two different Java programs to add two numbers. In the first program, we will specify the value of both the numbers in the program itself. However, on the second programs it will take both the numbers (entered by user) and prints the sum accordingly for Addition of Two numbers in Java Program.

lets go though the programs given here below.

Addition of Two numbers in Java Program

First Java Program Example: Sum of two numbers inputs within Program

public class AddTwoNumbers {

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

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

Output:

Sum of these numbers: 50

Second Java Program Example: Sum of two numbers using input by User

In this program User will be allowed to input the number as user input so that we can get the values of both the numbers from user. This program will then calculates the number sum and displays it as per user inputs.

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: 
100
Enter Second Number: 
50
Sum of these numbers: 150

Leave a Comment