×

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

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to...

2 minutes read.

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.

Java IO file not found exception

One of the exception classes offered by the java.io package is FileNotFoundException. An exception is raised when we attempt to access a file that isn't present in the system. It...

4 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.

Java Enum

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four iterators named Club, Diamond,...

3 minutes read.

Java Boolean logicalXor() Method

The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands. Syntax: public static boolean logicalXor (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Java String hashCode() method

Java String hashCode() method returns hash code for current String. hash code for string object is computed as s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] Using int...

2 minutes read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

Different Ways to Print Exception Message in Java

In this section, we will learn how to use various Java Throwable class methods to print exception messages. The Throwable class has the three methods listed below for printing the...

4 minutes read.

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.