Java Program to Add Two Integers
In this program, you'll learn to store and add two integer numbers in Java. After addition, the final sum is displayed on the screen.
The integer is stored in a variable using System.in, and is displayed on the screen using System.out.
To understand this example, you should have the knowledge of the following Java programming topics:
1. Add Two Integers (Hardcoded)
In this example, we store the numbers directly in the code.
public class AddIntegers {
public static void main(String[] args) {
int first = 10;
int second = 20;
System.out.println("First Number: " + first);
System.out.println("Second Number: " + second);
// add two numbers
int sum = first + second;
System.out.println("The sum is: " + sum);
}
}Output:
First Number: 10
Second Number: 20
The sum is: 302. Add Two Integers (User Input)
Here, we use the Scanner class to take input from the user.
import java.util.Scanner;
public class AddInput {
public static void main(String[] args) {
// Create a Scanner object
Scanner reader = new Scanner(System.in);
System.out.print("Enter two numbers: ");
// Read integers
int first = reader.nextInt();
int second = reader.nextInt();
int sum = first + second;
System.out.println("The sum is: " + sum);
// Close the scanner
reader.close();
}
}Output:
Enter two numbers: 10 20
The sum is: 30Explanation
int first = 10;: Declares an integer variable and assigns a value.Scanner reader = new Scanner(System.in);: Creates aScannerobject to read input from the standard input (keyboard).reader.nextInt(): Reads the next integer from the input.first + second: The+operator adds the two numbers.
Try Yourself
- Change Values: Change the hardcoded values to
100and200. - Add Three Numbers: Modify the program to add three integers instead of two.
- Negative Numbers: What happens if you enter
-5and10? Try it. - String Concatenation: Try
System.out.println("Sum: " + first + second);(without parentheses aroundfirst + second). Does it add or join? - Brain Twister: What happens if you try to add two very large numbers (e.g.,
2000000000+2000000000)? Hint: Integer Overflow.
Java Program to Print an Integer
In this program, you'll learn to print a predefined number aw well as a nummber entered by the user in Java.
Java Program to Swap Two Numbers
Learn different ways to swap two numbers in Java — using a temporary variable, arithmetic operations, and bitwise XOR — with clear examples and outputs.
