HomeJavaJava Program to Add Two Integers

Java Program to Add Two Integers

In this Java tutorial, we will learn how to add two integers in JAVA and storing the integer in an variable.

How to Add Two Integers in Java?

RUN CODE SNIPPET

Example 1:

Add Two Numbers

class Main {  

  public static void main(String[] args) {  

    System.out.println("Enter the two numbers");  

    int a = 12;  

    int b = 23;  

    System.out.println(a + " " + b);  

    int c = a + b;  

    System.out.println("The sum of two numbers is: " + c);  

  }  

}

Output 

Enter the two numbers 

12 23 

The sum of two numbers is: 35
  • In the example 1 we have two integers 12 and 23 are stored in integer values a and b. 
  • To add a and b we use + operator, and the result is stored in another variable called c. 
  • To display the sum of the two integers in screen we use println function. 

Example 2:

  • To get input from the user we use scanner class. The scanner class belongs to java.util.
RUN CODE SNIPPET
import java.util.Scanner; 

public class Main { 

    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: 

12 

Enter Second Number: 

21 

Sum of these numbers:33
  • In example 2 the scanner allows the user to enter the input, the two numbers 12 and 21 are stored in the integer values num1 and num2. 
  • To add the two numbers, we use + operator and the result is stored in the sum variable.

Leave a Reply

You May Also Like

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022