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.