Learn to write a simple Java program to add two integers and display their sum in the console.
1. Java example to add two integers
In given Java exmple, we have three int type variables i.e. firstInteger, secondInteger and sum.
We have assigned values to the first two integers, and then we have added them. The sum of the integers are added in third variable sum.
Finally, the sum has been printed in the screen with the System.out.println statement.
public class AddTwoIntegers
{
public static void main(String[] args)
{
int firstInteger = 10;
int secondInteger = 20;
int sum = firstInteger + secondInteger;
System.out.println("The sum of both integers: " + sum);
}
}
Program output
The sum of both integers: 30
2. Java program to add two integers entered by user
In the given Java example, we will take the two inters inputs from the user and after adding both integers, we will store their sum in the variable sum.
Finally, the sum has been printed in the screen with the System.out.println statement.
import java.util.Scanner;
public class AddTwoIntegers
{
public static void main(String[] args)
{
int firstInteger = 0;
int secondInteger = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
firstInteger = sc.nextInt();
System.out.println("Enter Second Number: ");
secondInteger = sc.nextInt();
sc.close();
int sum = firstInteger + secondInteger;
System.out.println("The sum of both integers: " + sum);
}
}
Program output
Enter First Number: 10 Enter Second Number: 20 The sum of both integers: 30
Happy Learning !!
Comments