TeachingBee

Different Ways To Add Two Numbers In Java

Add Two Numbers In Java

Addition two numbers in java is a fundamental concept in programming. This article explains different techniques to add two numbers in Java. We will discuss:

  • Standard approach Using hardcoded values
  • Standard approach Using User Input Values
  • Standard approach Using Command Line Arguments
  • User Defined Method
  • Inbuilt Sum() function

So, let’s get started.

Addition Of Two Numbers In Java

Before proceeding to solutions let’s first understand the problem statement with examples.

Problem Statment

Write a program that takes two numbers as input and add two numbers in Java.

For Example:

Enter the first number: 10 
Enter the second number: 20

Output:

The sum of 10 and 20 is: 30

Different Ways To Add Two Numbers In Java

Let’s look into different ways how we can add two numbers in Java.

1. Standard approach Using Hardcoded Values

In this approach, the values of the two numbers are directly specified within the code, and there’s no user input involved.

Addition Program In Java By Using Hardcoded Input Values

// Java program to add two numbers

public class AdditionExample {
    public static void main(String[] args) {
        int num1 = 5;
        int num2 = 7;
        int sum = num1 + num2;
        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
    }
}

Output

The sum of 5 and 7 is: 12

Explanation
The values of num1 and num2 are directly assigned in the code. The program calculates their sum and prints the result.

2. Standard approach Using User Input Values

In this approach, the values of the two numbers are taken as input from the user during runtime using the Scanner class.

Addition Program In Java Using User Input Values

// Java program to add two numbers by taking user input

import java.util.Scanner;

public class UserInputAddition {
    public static void main(String[] args) {
        // Create a Scanner object to take input from the user
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter the first number
        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();

        // Prompt the user to enter the second number
        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();

        // Calculate the sum of the two numbers
        int sum = num1 + num2;

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

        // Close the Scanner to prevent resource leak
        scanner.close();
    }
}

Output

Enter the first number: 8
Enter the second number: 6
The sum of 8 and 6 is: 14

Explanation
The program prompts the user to input two numbers, reads the values using the Scanner class, calculates their sum, and then prints the result.

3. Standard approach Using Command Line Argument

In this approach, the values of the two numbers are provided as command-line arguments during program execution.

In Java, command-line arguments are passed to the main method when a program is executed from the command line. The main method has a parameter called args, which is an array of strings. Each element in this array corresponds to a command-line argument.

When you run a Java program from the command line, you can include additional values after the program’s name.

java YourProgramName arg1 arg2

You can access individual command-line arguments by indexing into the args array.

int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);

Here, args[0] is the first command-line argument, and args[1] is the second.

Addition Program In Java By Using Command Line arguments

public class CommandLineAddition {
    public static void main(String[] args) {
        // Check if exactly two command-line arguments are provided
        if (args.length != 2) {
            System.out.println("Please provide two numbers as command-line arguments.");
            return;
        }

        // Parse the first command-line argument as an integer
        int num1 = Integer.parseInt(args[0]);

        // Parse the second command-line argument as an integer
        int num2 = Integer.parseInt(args[1]);

        // Calculate the sum of the two numbers
        int sum = num1 + num2;

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

Output

$ java CommandLineAddition 3 9
The sum of 3 and 9 is: 12

Explanation
The program checks if two command-line arguments are provided. If yes, it converts them to integers and calculates their sum, then prints the result. If not, it prompts the user to provide the required inputs.

4. Using User-Defined Function

In this approach, we utilise a user-defined function to encapsulate the addition logic, making the code modular and reusable.

Addition Program In Java Using User Defined Function

import java.util.Scanner;

public class UserDefinedFunctionAddition {
    public static void main(String[] args) {
        // Create a Scanner object to take input from the user
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter the first number
        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();

        // Prompt the user to enter the second number
        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();

        // Call the user-defined function to add two numbers
        int result = addNumbers(num1, num2);

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

        // Close the Scanner to prevent resource leak
        scanner.close();
    }

    // User-defined function to add two numbers
    public static int addNumbers(int a, int b) {
        return a + b;
    }
}


The addNumbers function takes two integers as parameters, adds them, and returns the result.

Output

Enter the first number: 5
Enter the second number: 7
The sum of 5 and 7 is: 12

Explanation
The main method takes user input, calls the addNumbers function to perform the addition, and then displays the result.

5. Using Inbuilt Sum() Method

In Java, the Integer.sum() method is a utility method introduced in Java 8 to simplify the addition of two integer values. It provides a convenient and efficient way to add two integers without the need for manual casting or arithmetic operations.

Addition Program In Java Using Sum() Method

public class AddTwoNumbers {
    public static void main(String[] args) {
        // Two numbers to be added
        int num1 = 5;
        int num2 = 10;

        // Using Integer.sum() to add two numbers
        int sum = Integer.sum(num1, num2);

        // Displaying the result
        System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);
    }
}

Output

Sum of 5 and 10 is: 15

Explanation

In the above example the Integer.sum() method is used to add num1 and num2, and the result is stored in the variable sum.

Sum of n Numbers

Till now we discussed how to add two numbers in Java, let’s now generalise the approach to find sum on n numbers in java.

Approach

  1. Use a loop to take input from the user n times.
  2. Accumulate the entered numbers to calculate the sum.
  3. Display the final sum.

Addition Of N Numbers Program In Java

import java.util.Scanner;

public class SumOfUserProvidedNumbers {
    public static void main(String[] args) {
        // Scanner to read input from the user
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter the value of n
        System.out.print("Enter the value of n: ");
        int n = scanner.nextInt();

        // Initialize sum to store the cumulative sum
        int sum = 0;

        // Take input from the user n times
        for (int i = 1; i <= n; i++) {
            System.out.print("Enter number " + i + ": ");
            int num = scanner.nextInt();
            sum += num;
        }

        // Close the scanner to avoid resource leak
        scanner.close();

        // Display the result
        System.out.println("Sum of the entered " + n + " numbers is: " + sum);
    }
}

Output

Enter the value of n: 3
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Sum of the entered 3 numbers is: 60

Explanation

  1. The above program uses a Scanner to take user input for the value of n.
  2. A for loop is employed to iterate from 1 to n.
  3. Inside the loop, the program prompts the user to enter a number, reads the input, and adds it to the sum variable.
  4. After the loop completes, the program prints the sum of the entered n numbers. In the provided example, it displays “Sum of the entered 3 numbers is: 60“.

Key Takeaways

  • Hardcoded values can be added directly but don’t allow customization
  • User input with Scanner class enables dynamic specification of numbers
  • Command-line arguments provide values when invoking the Java program
  • Custom methods modularize the addition logic for reuse
  • Utility methods like Integer.sum() simplify built-in operations
  • Loops allow adding larger sets of numbers entered by the user


Checkout more Java Tutorials here.

Similar Posts

Strong Numbers.

Add Days To The Current Date in Java

Calculate Area of Hexagon in Java

Program to Calculate EMI in Java

Calculate Area of a Circle in Java

Leap Year Program In Java

I hope You liked the post 👍. For more such posts, 📫 subscribe to our newsletter. Try out our free resume checker service where our Industry Experts will help you by providing resume score based on the key criteria that recruiters and hiring managers are looking for.

FAQ

How to add two numeric string in Java?

How to add numbers in set in Java?

How do you add three numbers in Java?

90% of Tech Recruiters Judge This In Seconds! 👩‍💻🔍

Don’t let your resume be the weak link. Discover how to make a strong first impression with our free technical resume review!

Related Articles

ascii value in java

Print ASCII Value in Java

In this article we will into the ASCII table in C, exploring its various character sets—from control characters to printable characters, including letters, digits, and special symbols—and demonstrates how to

data hiding in java

Data Hiding In Java

In this article we will discuss data hiding in Java which is an important concept in object-oriented programming. We will cover So let’s get started. What is Data Hiding in

Why Aren’t You Getting Interview Calls? 📞❌

It might just be your resume. Let us pinpoint the problem for free and supercharge your job search. 

Newsletter

Don’t miss out! Subscribe now

Log In