In this article, we will understand how to add two numbers in Java. This can be done using the '+' operator.
Below is a demonstration of the same −
Input
Suppose our input is −
input_1 : 10 input_2 : 15
Output
The desired output would be −
Sum : 25
Algorithm
Step1- Start Step 2- Declare three integers: input_1, input_2 and sum Step 3- Prompt the user to enter two integer value/ define the integers Step 4- Read the values Step 5- Add the two values using an addition operator (+) Step 6- Display the result Step 7- Stop
Example 1
Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool .
import java.util.Scanner; public class NumberAddition{ public static void main(String[] args){ int input_1, input_2, my_sum; Scanner my_scanner = new Scanner(System.in); System.out.println("A reader object has been defined "); System.out.println("Enter the first number: "); input_1 = my_scanner.nextInt(); System.out.println("Enter the second number: "); input_2 = my_scanner.nextInt(); my_scanner.close(); System.out.println("The scanner object has been closed"); my_sum = input_1 + input_2; System.out.println("Sum of the two numbers is: "); System.out.println(my_sum); } }
Output
A reader object has been defined Enter the first number: 23 Enter the second number: 45 The scanner object has been closed Sum of the two numbers is: 68
Example 2
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
public class NumberAddition{ public static void main(String[] args){ int value_1, value_2, my_sum; value_1 = 10; value_2 = 15; System.out.printf("The two numbers are %d and %d",value_1, value_2 ); System.out.printf("\n"); my_sum = value_1 + value_2; System.out.println("The numbers have been added using '+' operator"); System.out.println("\nSum of the two numbers is : "); System.out.println(my_sum); } }
Output
The two numbers are 10 and 15 The numbers have been added using '+' operator Sum of the two numbers is : 25