Java: Print the sum of two numbers
Sum of Two Numbers
Write a Java program to print the sum of two numbers.
In mathematics, summation (capital Greek sigma symbol: ∑) is the addition of a sequence of numbers; the result is their sum or total. The numbers to be summed may be integers, rational numbers, real numbers, or complex numbers.
Pictorial Presentation:

Sample Solution:
Java Code:
public class Exercise2 {
public static void main(String[] args) {
// Calculate the sum of 24 and 26
int sum = 24 + 26;
// Print the result of the addition
System.out.println(sum);
}
}
Explanation:
This Java code defines a class called 'Exercise2' with a 'main' method. When executed, it prints the result of the arithmetic expression '24 + 26' to the console, which is '50'.
Sample Output:
50
Flowchart:

Sample solution using input from the user:
Java Code:
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
// Create a Scanner object to read input from the user
Scanner input = new Scanner(System.in);
// Prompt the user to input the first number
System.out.print("Input the first number: ");
// Read and store the first number
int num1 = input.nextInt();
// Prompt the user to input the second number
System.out.print("Input the second number: ");
// Read and store the second number
int num2 = input.nextInt();
// Calculate the sum of the two numbers
int sum = num1 + num2;
// Display a blank line for separation
System.out.println();
// Display the sum of the two numbers
System.out.println("Sum: " + sum);
}
}
Explanation:
The above Java code takes two numbers as input from the user, calculates their sum, and then displays the result. It uses the Scanner class to read user input and performs basic arithmetic.
Sample Output:
Input the first number: 256 Input the second number: 326 Sum: 582
Flowchart:

For more Practice: Solve these Related Problems:
- Write a program that reads three numbers and prints their sum.
- Write a program that takes two floating-point numbers as input and prints their sum rounded to 2 decimal places.
- Modify the program to add two numbers but handle integer overflow gracefully.
- Print the sum of two numbers without using the '+' operator.
Java Code Editor:
Previous: Write a Java program to print 'Hello' on screen and then print your name on a separate line.
Next: Write a Java program to divide two numbers and print on the screen.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics