Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction 
2.
Method 1: Sum of Two Numbers
2.1.
Java Code
3.
Method 2: Add Two Numbers Using User Input
3.1.
Java Code
4.
Method 3: Sum of Two Numbers Using Command Line Arguments in Java
4.1.
Java Code
5.
Method 4: Sum of Two Numbers in Java Using Method
5.1.
By using a user-defined method
6.
Java Code
6.1.
By using the sum() method
7.
Java Code
8.
Method 5: Sum of 3 Numbers in Java
8.1.
Java Code
9.
Method 6: Sum of N Numbers in Java
9.1.
Java Code
10.
Integer Overflow
10.1.
Java Code
11.
Frequently Asked Questions
11.1.
How to add two numbers in Java?
11.2.
What is the sum of += in Java?
11.3.
How to add two numbers in an array in Java?
11.4.
How to add two string integer in Java?
12.
Conclusion
Last Updated: Mar 27, 2024
Easy

Addition of Two Numbers in Java

Author Gaurav Joshi
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction 

Adding two numbers often seems to be too easy. What if I told you there are different ways through which a simple addition program could be performed in Java? Different Java programs for the addition of two numbers in Java are explained in simple language in the article; we have also discussed different ways through which users can provide input and much more.

Addition uses the "+" operator for adding two numbers.

addition of two numbers in java

Let us now look at the ways in which we can add two numbers in Java.

Method 1: Sum of Two Numbers

You can find the sum of two numbers by using the addition operator in Java. The result can be printed using System.out.println.

The following code illustrates the addition of two numbers in Java:-

Implementation
 

  • Java Code

Java Code

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

 

Output:- 

The sum of 5 and 10 is: 15

 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Method 2: Add Two Numbers Using User Input

In this section, we have discussed the Java program to add two integers where both integers are provided by the user and collected by the object of the scanner class. 

Implementation

  • Java Code

Java Code

// Import the Scanner class
import java.util.Scanner;

class Add_2_Numbers {
 public static void main(String[] args) {

   // Creating a Scanner class object
   Scanner scan = new Scanner(System.in);
   System.out.println("Enter the first number : ");

   // Reading user input
   int num1 = scan.nextInt();

   System.out.println("Enter the second number : ");

   // Reading user input
   int num2 = scan.nextInt();
  
   // Calculate the sum with help of addition operator
   int sum = num1 + num2;
  
   // Close the scanner
   scan.close();

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


Output:-

Enter the first number : 
10
Enter the second number : 
20
The Sum of 10 and 20 is: 30

 

Try it by yourself on Java Online Compiler.

Method 3: Sum of Two Numbers Using Command Line Arguments in Java

Another method of taking input from users is command-line arguments. In this section, we have discussed the Java program to add two integers where both integers are provided by the user using arguments from the command line.

Implementation

  • Java Code

Java Code

public class Add_2_Numbers{
public static void main(String[] args){
  
   // Reading user input
   int num1 = Integer.parseInt(args[0]);
   System.out.println("The First number is: "+num1);

   // Reading user input
   int num2 = Integer.parseInt(args[1]); 
   System.out.println("The Second number is: "+num2);

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

   }
}


Output:-

Command-line arguments: 10 20
The first number is: 10
The second number is: 20
The sum of 10 and 20 is: 30

 

Know about Single Inheritance in Java in detail.

Method 4: Sum of Two Numbers in Java Using Method

Let us now discuss the Sum of Two Numbers using using methods: 

By using a user-defined method

In the following code sample, the sum function expects two integers as input and returns their sum.

Implementation

  • Java Code

Java Code

public class Main {
public static int sum(int x, int y) {
return x + y;
}
public static void main(String[] args) {
int num1 = 2;
int num2 = 3;
int result = sum(num1, num2);
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + result);
}
}


Output:-

The sum of 2 and 3 is: 5


Next, let us see the built-in sum() method in java: 

By using the sum() method

The sum() method of Java integer class returns the sum of the two given arguments. 

The following code illustrates the same:-

Implementation 

  • Java Code

Java Code

public class Main {
public static void main(String[] args) {
int num1 = 2;
int num2 = 4;
int result = Integer.sum(num1, num2);
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + result);
}
}


Output:-

The sum of 2 and 4 is: 6

Method 5: Sum of 3 Numbers in Java

The addition operator can be used consecutively. The following code sample illustrates adding 3 integers and displaying them:-

Implementation

  • Java Code

Java Code

public class Main {
public static void main(String[] args) {
int num1 = 5;
int num2 = 10;
int num3 = 15;

int sum = num1 + num2 + num3;

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


Output:- 

The sum of the three numbers is: 30

Method 6: Sum of N Numbers in Java

Let us now discuss the next method where we find the sum of N numbers: 

Sum of N Numbers in Java

In order to add N numbers, you need to keep a sum variable that keeps track of the in your for loop. The integers can be stored in an array.

The following code traverses over a given array while adding the value of each element to the sum variable.

Implementation

  • Java Code

Java Code

public class Main {
public static void main(String[] args) {
int[] nums = { 5, 10, 15, 20, 25 }; // Example array of numbers
int sum = 0;

for (int i = 0; i < nums.length; i++) {
sum += nums[i];
}

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


Output:- 

The sum of the numbers is: 75


If the sum of integers in the given array exceeds the maximum value that an ‘int’ can store in Java, an integer overflow occurs. You will get to know more about it in the next section.

Must see, Nmap commands

Integer Overflow

This condition occurs when you try to store a value larger than the limit of an integer. It usually occurs after performing some arithmetic operations involving many large integers. The following code sample illustrated the condition:-

Implementation

  • Java Code

Java Code

public class Main {
public static void main(String[] args) {
int maxValue = Integer.MAX_VALUE; // Maximum value of int

System.out.println("Max Value: " + maxValue);

int overflow = maxValue + 1; // Causes integer overflow

System.out.println("Overflow Value: " + overflow);
}
}


Output:-

Max Value: 2147483647
Overflow Value: -2147483648


Adding one to the maximum value of the integer resulted in it becoming the lowest value that an integer can store. This is due to a wraparound behavior that is not present in C and C++.

Read also - Strong number in c

Frequently Asked Questions

How to add two numbers in Java?

The addition of two numbers in Java is very easy. Declare two variables and initialize those variables with some value. The next is to use another variable that will store the addition of the above-declared variables using the addition operator. 

What is the sum of += in Java?

The += operator in Java is a shorthand assignment operator that is used for performing addition and assignment in a single step. The right-hand side value is added to the variable on the left-hand side and then assign the result to the left-hand side.

How to add two numbers in an array in Java?

To add two numbers in an array in Java, it is compulsory that the length of both the array must be the same. Create two arrays of the same length and initialize them with some values and later create a new array that will store the addition of two previous arrays. 

How to add two string integer in Java?

Java uses the addition operator for both addition and concatenation. When you declare two variables, either two variables of string integers or one string and one integer variable, the addition is the concatenation of both variables.

Conclusion

In the article, we have extensively discussed the addition of two numbers in Java.

Recommended Readings:

Check out this problem - Check If A String Is Palindrome
 

We hope that this blog has helped you enhance your knowledge regarding the java programming language. If you would like to learn more about such content and practice some quality questions that require you to excel your preparations a notch higher. In that case, you can visit our Guided Path in  Coding Ninjas Studio.To be more confident in data structures and algorithms, try out our DS and Algo Course. Until then, All the best for your future endeavours, and Keep Coding.

Live masterclass