×

Addition Program in Java

Addition Program in Java

We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand how the + operator works. In this section, we will create Java programs that add two or more numbers.

Using Command-Line Arguments

Filename: AdditionExample1.java

class AdditionExample1
{
public static void main(String[] args)
{
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int sum = x + y;
System.out.println("The sum is: " +sum);
}
}

Output:

The sum is: 17

Explanation: In the above example, a point to be noted that we have not initialized any number. Instead of initializing the number, we will pass the numbers as argument at the time when we specify the java command.

java AdditionExample1 8 9 

The first argument will be store in the variable x and the second argument will be store in the variable y. Remember that the numbers that we have parsed as an argument in String and we cannot perform the addition. So, we need to convert these arguments in the integer by using the parseInt() method of the Integer class.  

Let’s see another program.

Filename: AdditionExample2.java

public class AdditionExample2
{             
public static void main(String[] args)
{
               int a = 5, b = 6; //a and b are two operands
               int add; //a variable that stores the final result
               add = a + b; //performing the addition operation
               //printing the result
System.out.println("Addition of " + a + " and " + b + " is " + add);
}
}

Output:

Addition of 5 and 6 is 11

The addition operation is not only confined to two operands. We can have n numbers of operands on which we can perform the addition operation. In such a scenario, we either take the help of Java for loop (iterative approach), or we choose the recursive approach. Let’s discuss the iterative approach first.

Iterative approach

The following program demonstrates how to add array elements.

Filename: AdditionExample3.java

public class AdditionExample3
{             
public static void main(String[] args)
{
               int arr[] = {4, 56, 230, 5, 598, 232, 348, 23, 54, 2, 72, 4, 345};
               int add = 0; //a variable that stores the result
               //Iterating over every element of the array and performing addition
               for(int i = 0; i < arr.length; i++)
                               add += arr[i];
               //printing the result
System.out.println("Total sum is: " + add);
}
}

Output:

Total sum is: 1973

Explanation: In the above example, we have created an array arr[] and inserted some numbers into it. We have taken another variable add and initialized it to 0. It stores the sum of numbers that array contains. We have used a Java for loop that iterate over the array and fetch the numbers. After that, we are finding the cumulative sum and storing the sum in the addvariable.

We can achieve the same result using the recursion, also.

Recursive Approach

Filename: AdditionExample4.java

public class AdditionExample4
{
public static int addUsingRec(int input[], int index)   
{
               //handling the base case
               if(index >= input.length) return 0;
               //recursively adding numbers
               return input[index] + addUsingRec(input, index + 1);
}
public static void main(String[] args)
{
               int arr[] = {4, 56, 230, 5, 598, 232, 348, 23, 54, 2, 72, 4, 345};
               int add; //it will contain the final result
               add = addUsingRec(arr, 0); //storing the result
               //printing the result
System.out.println("Total sum is: " + add);
}
}

Output:

Total sum is: 1973

Explanation: The approach is similar to the iterative one. The only difference is instead of Java-for loop, we have used the recursion for doing the iteration.


Related Topics

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

How to remove special characters from String in Java

Strings in Java are Objects that are supported inside by a burn exhibit. Since exhibits are immutable (cannot develop), Strings are changeless too. A completely new String is made whenever...

5 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

How to check data type in Java

In this section, we will learn about the methodology to verify the data type in Java. There are mainly two methods in java called as getClass() and getName(). They are...

3 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.

Caesar Cipher Program in Java

It is among the most popular and straightforward encryption methods. With this method, each letter in the text is swapped out for a letter that is a certain number of...

3 minutes read.

How to Read CSV Files in Java?

Comma-Separated Values is the acronym for this format. It is a straightforward file format storing textual tabular data in a database or spreadsheet. The CSV files can be imported into...

3 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Java String length() method

Java String length() method returns length of the characters in a String. Syntax: public int length() Returns It returns length of the characters Java String length() method example 1          public class JavaStringLengthEx1  ...

1 minute read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Java Pop

The array, linked list, stack, queue, and other data structures are supported by Java programming. The insertion, deletion, and element searching operations are available for every data structure. And Java...

4 minutes read.

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 minutes read.

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.