Java Program to Add Two Numbers

You are currently viewing Java Program to Add Two Numbers

In this article, I’m going to teach the concept of the java program to add two numbers. Below. We can see the two example programs to add two numbers in java. Let’s start the article.

Java Program to Add Two Numbers

Now, We can apply the two input values into the program directly to add two numbers in java.

public class AddTwoNumbers {

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

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

Execution

Firstly, We have to assign the respective variables and provide the two input values. After executing this program, The two input integers will be added using the condition (sum=num1+num2).

Later, The new output will be stored in the “sum” variable. Finally, The system.out.printIn() function will display the result on the output screen.

Output

The output will show below for your reference.

Sum of these numbers: 43
Read Also : Java Program to Subtract Two Numbers

Note

If you want to Add Two Numbers in JavaScript and Add Two Numbers in AngularJS then please read those articles that we have already posted on our webpage.

Java Program to Add Two Numbers

This example program will be based on the user input to add two numbers in java.

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);
    }
}

Explanation

Initially, We have to import the java.util.scanner class into this program. Secondly, We need to declare the three respective variables like “num1”, “num2”, and the “sum”.

After running this program, The program asks you to enter the two input values using the new scanner() function. After entering the values, The input values will be added using the (sum=num1+num2) condition.

Finally, We will see the output on the screen using the system.out.printIn() function.

Output

The output of the java program to add two numbers will be shown below for your reference.

Enter First Number: 
10
Enter Second Number: 
10
Sum of these numbers: 20

Final Thoughts

I hope this article helps you to Add Two Numbers using Java. If you face any issues please let me know via the comment section. Share this article with other Java developers via social networks. Thank You!

Manoj S

Hi, I'm Manoj working as a part-time blogger in Coding Diksha. Here, I post about programming to help developers.

Leave a Reply