Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconHow to Add Two Numbers in Java?

How to Add Two Numbers in Java?

Last updated:
4th Jun, 2023
Views
Read Time
5 Mins
share image icon
In this article
Chevron in toc
View All
How to Add Two Numbers in Java?

Given below is the flowchart depicting the addition of two numbers. The process is very simple. We are supposed to input two numbers and add them up. Save the answer in Sum and display the result.

Image Source: Google 

Now we will take the next jump and see two programs for the addition of two numbers in Java. In the first example, we assign a value of the two numbers within the code. The second program takes the two numbers passed by the user and displays the sum.

Ads of upGrad blog

How To Add Two Numbers In Java?

In Java, adding two numbers requires adding two integers and printing the result. Adding two numbers in the Java programming language is straightforward; let’s look at the algorithm.

Algorithm

Below mentioned is the most basic algorithm for the addition of two numbers in Java :

  • Introduce two variables.
  • Set some values as initial values for the variables.
  • Set up a second variable to hold the total of the numbers.
  • Add two values together using the plus (+) operator in mathematics, then save the outcome.

Sum Of Two Numbers Using Method

Here are two methods to add two numbers in Java:

  • Using sum() method
  • Using User-defined method

sum() method

sum() is a function available in the integer class. Given below is a simple Java program to add two numbers using the sum() method.

Example code:

class AddTwoNumbers

{    

    public static void main(String args[])   

    {            

        int m = 1, m = 2, x = 3, y = 4, reqsum1, req_sum2;    

        reqsum1=Integer.sum(m, n);  

        System.out.println(“Given sum of m and n is: ” +req_sum1);    

       reqsum2=Integer.sum(x, y);  

        System.out.println(“Given sum of x and y is: ” +req_sum2);  

    }    

}   

Output:

Given sum of m and n is: 3

Given sum of x and y is: 7

User-defined method

The user can read input in Java and enter two numbers. Next, they will send it to the user-defined method sum().

The Java program to add two numbers using a user-defined method is implemented below.

Class AddTwoNumbers

{  

    public static void main(String args[])  

    {  

        int a, b, req_sum;  

        Scanner sc = new Scanner(System.in);  

        a = sc.nextInt();  

        b = sc.nextInt(); 

        req_sum = final_sum(a, b);  

        System.out.println(“Sum of numbers ” + a + ” and ” + b + ” is: ” +reqsum );  

    }   

    public static int final_sum(int m, int n)  

    {  

        int final_sum = m + n;  

        return final_sum;  

    }  

}  

Sum Of 3 Numbers

The sole difference between the sum of three numbers and the sum of two numbers is that there are three variables in this case.

Sum Of N Numbers 

This method of figuring out the sum of ‘N’ numbers is more inclusive. Below is the general algorithm to find the sum of ‘N’ numbers in Java.

  • The number of integers to be added, N, should be initialised.
  • The loop will repeat N times and prompt the user for input, or it may not, depending on how the loop is initialised.
  • Put the sum of each input’s values into a variable.
  • Once all iterations have been completed, print the sum value.

Check out our free technology courses to get an edge over the competition.

Example 1: Finding the sum of two numbers

Output:

Image Source: Google

If we observe in the above-given program, we’ll find out that the values of the numbers are specified in the program.

Check Out upGrad’s Software Development Courses

Example 2: Use of Scanner to compute the sum of two numbers

What is a scanner?

The scanner helps us to capture the input given by the user so that the values of the two numbers can be obtained from the user. Then, the program computes the sum and shows it as output.

Image Source: Google

Explore our Popular Software Engineering Courses

If we see in the above program, we’ll find that at the end of the program, both the numbers are required to be furnished by the user and then the sum is calculated and displayed at the end.

Third Example: Sum of two numbers Using command line arguments 

The aforementioned method is not the only way to add two numbers. You can add two number using command line arguments as well. Check out the program given below to learn and understand how to add two numbers with command line arguments:

Image Source : Google

In-Demand Software Development Skills

Output :

Ads of upGrad blog

Image Source: Google

If you want to learn how to add two numbers in Java, you can use the aforementioned methods. There are other methods as well that you can use to do the same, like Using Buffered Reader, Using Method, Without Using Addition+ Operator, & Using Classes and Objects.

At upGrad, we understand the importance of practical, hands-on learning – especially when it comes to software development. As a result, our courses and training initiatives have practicality at their very core. One such initiative is Full Stack Development Bootcamp which will help you develop all the relevant skills required to excel in full-stack development. 

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.

Explore Free Courses

Suggested Blogs

DevOps Engineer Salary in India in 2023 [For Freshers & Experienced]
901790
Wondering what is the range of DevOps Salary in India? In the last few years, DevOps has evolved from being just a “buzzword” to a mainstream practic
Read More

by upGrad

07 Nov 2023

What Is AWS Route 53 and How Does It Work?
1298
Managing domain names and directing traffic efficiently is pivotal in the intricate web of cloud computing and web hosting. Enter AWS Route 53, Amazon
Read More

by Pavan Vadapalli

29 Sep 2023

Agile vs Scrum: Difference Between Agile and Scrum
2047
Keeping up with the fast-paced nature of project development fueled by technological progress is challenging, to say the least. To function efficientl
Read More

by Pavan Vadapalli

28 Sep 2023

What Is Azure Active Directory? A Complete Guide
1302
In the ever-evolving landscape of cloud computing, Azure Active Directory or Azure AD has emerged as a cornerstone in identity and access management.
Read More

by Pavan Vadapalli

28 Sep 2023

Difference Between Product Backlog and Sprint Backlog: A Quick Guide
1251
Agile is a highly effective project management methodology, but its efficiency relies on the team’s collective understanding of key concepts, su
Read More

by Pavan Vadapalli

28 Sep 2023

Agile Manifesto Explained: Understanding Agile Values
1683
Manifestos are formal declarations of principles or beliefs that guide movements or ideologies. The impact of the Agile Manifesto principles has exten
Read More

by Pavan Vadapalli

28 Sep 2023

Top 22 Best Agile Project Management Tools in 2023
1471
The recent years have seen a surge in using the best Agile management tools and techniques, especially in software development. Breaking down projects
Read More

by Pavan Vadapalli

27 Sep 2023

Scrum Master Roles and Responsibilities: Everything You Should Know
1825
In today’s fast-paced business environment, organisations constantly seek ways to enhance their productivity, collaboration, and product quality
Read More

by Pavan Vadapalli

27 Sep 2023

What Is Programming Language? Syntax, Top Languages, Examples
1739
Computer programming is expanding daily, with new programming languages being launched yearly, adding to the list.  Renowned companies now look for co
Read More

by Pavan Vadapalli

25 Sep 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon