In this Java program, we will learn how to add two numbers entered by the user and display their sum using the Scanner class.
Java Program
import java.util.Scanner;
public class AdditionOfTwoNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = sc.nextInt();
System.out.print("Enter second number: ");
int num2 = sc.nextInt();
int sum = num1 + num2;
System.out.println("Sum = " + sum);
sc.close();
}
}
Output
Enter first number: 25
Enter second number: 15
Sum = 40
Explanation
The program uses the Scanner class to accept two numbers from the user.
int num1 = sc.nextInt();
int num2 = sc.nextInt();
The + operator is then used to add the two numbers:
int sum = num1 + num2;
Finally, the result is displayed using System.out.println().
Key Points
Scanneris used to read numbers from the user.- The
+operator performs addition. - The result is stored in the
sumvariable. System.out.println()displays the final result.
Conclusion
This simple Java program demonstrates how to take two numbers as input, perform addition, and display the result.