﻿ Java - Print the sum of two numbers

# Java: Print the sum of two numbers

## Java Basic: Exercise-2 with Solution

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: Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿