Java How to Add Two Numbers

Adding two numbers is one of the simplest tasks in programming, and it’s often the starting point for learning basic arithmetic operations. In Java, you can add two numbers using variables, user input, or even methods.

This tutorial by The Coding College will guide you through different ways to add two numbers in Java, ensuring a clear understanding and hands-on practice.

1. Adding Two Numbers Using Variables

This is the simplest method where two numbers are stored in variables, and their sum is calculated.

Example: Using Variables

public class Main {
    public static void main(String[] args) {
        int num1 = 10; // First number
        int num2 = 20; // Second number
        int sum = num1 + num2; // Adding the numbers

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

Output:

The sum of 10 and 20 is: 30

2. Adding Two Numbers Using User Input

In this method, the user enters two numbers, and the program calculates their sum.

Example: Using Scanner for User Input

import java.util.Scanner;

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

        System.out.print("Enter the first number: ");
        int num1 = scanner.nextInt();

        System.out.print("Enter the second number: ");
        int num2 = scanner.nextInt();

        int sum = num1 + num2; // Adding the numbers
        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);

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

Output:

Enter the first number: 15
Enter the second number: 25
The sum of 15 and 25 is: 40

3. Adding Two Numbers Using a Method

Encapsulating the addition logic in a method promotes code reuse and better readability.

Example: Using a Method

public class Main {
    public static int addNumbers(int a, int b) {
        return a + b; // Adding the numbers
    }

    public static void main(String[] args) {
        int num1 = 30;
        int num2 = 40;

        int sum = addNumbers(num1, num2); // Calling the method
        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
    }
}

Output:

The sum of 30 and 40 is: 70

4. Adding Two Floating-Point Numbers

To work with decimal numbers, use the float or double data types.

Example: Adding Floating-Point Numbers

public class Main {
    public static void main(String[] args) {
        double num1 = 12.5;
        double num2 = 15.75;

        double sum = num1 + num2; // Adding the numbers
        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
    }
}

Output:

The sum of 12.5 and 15.75 is: 28.25

5. Adding Numbers from Command-Line Arguments

You can pass numbers as command-line arguments and add them.

Example: Using Command-Line Arguments

public class Main {
    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("Please provide two numbers as arguments.");
            return;
        }

        int num1 = Integer.parseInt(args[0]); // Convert first argument to int
        int num2 = Integer.parseInt(args[1]); // Convert second argument to int

        int sum = num1 + num2; // Adding the numbers
        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
    }
}

Run the program:

java Main 10 20

Output:

The sum of 10 and 20 is: 30

6. Adding Large Numbers Using BigInteger

For extremely large numbers, Java provides the BigInteger class.

Example: Using BigInteger

import java.math.BigInteger;

public class Main {
    public static void main(String[] args) {
        BigInteger num1 = new BigInteger("123456789123456789");
        BigInteger num2 = new BigInteger("987654321987654321");

        BigInteger sum = num1.add(num2); // Adding the numbers
        System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
    }
}

Output:

The sum of 123456789123456789 and 987654321987654321 is: 1111111111111111110

Best Practices

  1. Input Validation: Always validate user input to avoid errors like NumberFormatException.
  2. Data Types: Choose the appropriate data type (int, float, double, or BigInteger) based on the expected range and precision of the numbers.
  3. Error Handling: Use try-catch blocks when converting strings to numbers to handle invalid input gracefully.

Conclusion

Adding two numbers in Java can be performed in multiple ways, depending on the requirements. Whether you’re using variables, user input, or advanced techniques like BigInteger, Java provides all the tools you need.

For more coding tutorials and practical examples, visit The Coding College. Keep learning and coding!

Leave a Comment