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 SNIPPETExample 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.
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.
 
															