How to Add Two Numbers in Java

Java is a widely used programming language, known for its simplicity and versatility. One of the most basic operations in any programming language is adding two numbers. In this quick tutorial, we'll walk you through how to add two numbers in Java.

Simple Code to Add Two Numbers

Here's a simple Java program that takes two numbers as input from the user and adds them together:


import java.util.Scanner; public class AddNumbers { public static void main(String[] args) { // Create a Scanner object to read input Scanner scanner = new Scanner(System.in); // Prompt user to enter two numbers System.out.print("Enter the first number: "); int num1 = scanner.nextInt(); System.out.print("Enter the second number: "); int num2 = scanner.nextInt(); // Add the numbers int sum = num1 + num2; // Display the result System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum); // Close the scanner to prevent memory leak scanner.close(); } }

Explanation

  1. Scanner Class: We use the Scanner class to get input from the user.

  2. Input Numbers: The program asks the user to enter two integers.

  3. Addition: It adds the two integers and stores the result in the variable sum.

  4. Output: Finally, the program displays the sum of the two numbers.

Conclusion

Adding two numbers in Java is a fundamental operation that every beginner should master. This simple program can be easily extended to handle more complex operations. If you're just getting started with Java, try modifying the program to add floating-point numbers or handle multiple operations!

Comments

Popular posts from this blog

Python features

How to Find GCD of Two Numbers in Java

Master AWS with the Best Training in Pune – Join Technogeeks Today!