Java Program to Add Two Numbers|

Java Program to add two numbers is one of the most fundamental operations in programming. In Java, you can perform this task using various methods. In this article, we’ll explore four different methods: Add Two Numbers in Java using the + operator directly, Add Two Numbers in Java user input, Add Two Numbers in Java using for loop for iterative addition, and creating a user-defined method. We’ll provide clear explanations and example code for each method.

Method 1: Using the + Operator

The simplest way to add two numbers in Java is by using the + operator. Here’s a code snippet demonstrating this method:

public class AddTwoNumbersUsingOperator {
    public static void main(String[] args) {
        double num1 = 5.5;
        double num2 = 3.0;

        double sum = num1 + num2;

        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
    }
}

In this code:

  • We declare two variables, num1 and num2, and initialize them with the numbers we want to add.
  • We use the + operator to add these numbers and store the result in the sum variable.
  • Finally, we print the sum to the console.

Understanding the Code :

  1. Class Declaration:
    • public class AddTwoNumbersUsingOperator {: This line defines a class named AddTwoNumbersUsingOperator.
  2. Main Method:
    • public static void main(String[] args) {: This is the entry point of the program where execution begins.
  3. Variable Declaration and Initialization:
    • double num1 = 5.5; and double num2 = 3.0;: These lines declare and initialize two double-precision floating-point variables num1 and num2 with the values to be added.
  4. Adding Numbers:
    • double sum = num1 + num2;: Here, we use the + operator to add num1 and num2, and the result is stored in the variable sum.
  5. Displaying the Result:
    • System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);: This line prints the sum of the two numbers to the console.

Method 2 : By User Input

import java.util.Scanner;

public class AddTwoNumbers {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the first number: ");
        double num1 = input.nextDouble();

        System.out.print("Enter the second number: ");
        double num2 = input.nextDouble();

        double sum = num1 + num2;

        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
    }
}

In the Code :

  • We begin by importing the java.util.Scanner class to allow user input.
  • The public class AddTwoNumbers line defines our class.
  • public static void main(String[] args) is the main method where our program starts execution.
  • We create a Scanner object to take user input.
  • The program prompts the user to enter two numbers.
  • It then calculates the sum and stores it in the sum variable.
  • Finally, it displays the result to the user.

Understanding the Code :

  1. Import Statement:
    • import java.util.Scanner;: This line imports the Scanner class from the java.util package. The Scanner class is used for taking user input.
  2. Class Declaration:
    • public class AddTwoNumbers {: This line defines a new class named AddTwoNumbers. In Java, every program must have at least one class, and the class name should match the filename (in this case, it’s AddTwoNumbers.java).
  3. Main Method:
    • public static void main(String[] args) {: This is the entry point of the Java program. All Java applications start from the main method.
  4. Creating a Scanner Object:
    • Scanner input = new Scanner(System.in);: Here, we create an instance of the Scanner class named input. This Scanner object will be used to read input from the user via the keyboard (System.in).
  5. User Input:
    • System.out.print("Enter the first number: ");: This line displays the message “Enter the first number: ” on the console.
    • double num1 = input.nextDouble();: This line reads a double-precision (floating-point) number entered by the user and stores it in the variable num1. The input.nextDouble() method is used to read the input.
    • Similar steps are repeated for the second number:
      • System.out.print("Enter the second number: ");
      • double num2 = input.nextDouble();
  6. Calculating the Sum:
    • double sum = num1 + num2;: This line calculates the sum of num1 and num2 and stores it in the variable sum.
  7. Displaying the Result:
    • System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);: Finally, this line displays the result to the user. It prints a message that includes the values of num1, num2, and the calculated sum.

Method 3: Using a for Loop

If you need to add a series of numbers, you can use a for loop for repetitive addition. Here’s an example:

public class AddNumbersUsingForLoop {
    public static void main(String[] args) {
        int[] numbers = {2, 4, 6, 8, 10};
        int sum = 0;

        for (int num : numbers) {
            sum += num;
        }

        System.out.println("The sum of the numbers is: " + sum);
    }
}

In this code:

  • We create an array named numbers containing a series of integers.
  • We initialize a variable sum to store the cumulative sum.
  • Using a for loop, we iterate through the array, adding each number to the sum.
  • Finally, we print the total sum to the console.

Understanding the Code :

  1. Class Declaration:
    • public class AddNumbersUsingForLoop {: This line defines a class named AddNumbersUsingForLoop.
  2. Main Method:
    • public static void main(String[] args) {: This is the program’s entry point.
  3. Array Declaration and Initialization:
    • int[] numbers = {2, 4, 6, 8, 10};: This line declares an integer array named numbers and initializes it with a series of integers.
  4. Variable Declaration and Initialization:
    • int sum = 0;: We declare an integer variable sum and initialize it to 0. This variable will hold the cumulative sum.
  5. Iterative Summation with for Loop:
    • for (int num : numbers) {: This for loop iterates through each element in the numbers array.
    • sum += num;: Inside the loop, each element num is added to the sum, effectively accumulating the total sum.
  6. Displaying the Result:
    • System.out.println("The sum of the numbers is: " + sum);: Finally, we print the total sum to the console.

Method 4: Using a User-Defined Method

To add two numbers using a user-defined method, we create a custom function that takes two parameters and returns the sum. Here’s an example:

public class AddNumbersUsingMethod {
    public static void main(String[] args) {
        double num1 = 7.5;
        double num2 = 4.3;

        double result = addTwoNumbers(num1, num2);

        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + result);
    }

    // User-defined method to add two numbers
    public static double addTwoNumbers(double a, double b) {
        return a + b;
    }
}

In this code:

  • We declare two variables, num1 and num2, and initialize them with the numbers to be added.
  • We call a user-defined method addTwoNumbers, passing num1 and num2 as arguments. This method returns the sum of the two numbers.
  • Finally, we print the result to the console.

Understanding the Code :

  1. Class Declaration:
    • public class AddNumbersUsingMethod {: This line defines a class named AddNumbersUsingMethod.
  2. Main Method:
    • public static void main(String[] args) {: This is the entry point of the program.
  3. Variable Declaration and Initialization:
    • double num1 = 7.5; and double num2 = 4.3;: These lines declare and initialize two double-precision floating-point variables num1 and num2 with the values to be added.
  4. Method Call:
    • double result = addTwoNumbers(num1, num2);: We call a user-defined method addTwoNumbers, passing num1 and num2 as arguments. The method returns the sum, which is stored in the result variable.
  5. User-Defined Method:
    • public static double addTwoNumbers(double a, double b) {: This section defines a user-defined method addTwoNumbers that takes two double parameters a and b and returns their sum using the return statement.
  6. Displaying the Result:
    • System.out.println("The sum of " + num1 + " and " + num2 + " is: " + result);: Finally, we print the result (sum) to the console.

Conclusion

Hope, you must have understood how to add two numbers in java ?, java program to add two numbers with all four methods : Add Two Numbers in Java using plus operator, Add Two Numbers in Java using for loop, Add Two Numbers in Java user input, Add Two Numbers in Java example. keep learning, keep exploring.

Hello Guys, Ayush this side. I am founder of studypunchx. I love to share trending and useful informations. keep Growing.....

Leave a Comment