Full Stack Web Development Internship Program
- 3k Enrolled Learners
- Weekend/Weekday
- Live Class
In this article, I am going to introduce you to a simple yet important concept that is addition of two numbers in Java. But before moving ahead, I would suggest you to get familiar with “What is Java”, features of Java and how can you install Java on your system, which you can find in previous blog. This will help you grab the coming concepts quickly and easily. The other blogs in this Java tutorial series written by our Java Training experts will cover all the important topics of Java & J2EE in depth,
Following pointers will be covered in this article,
Let’s understand directly by developing a program in Java to print “Addition of two numbers” on screen.
Class AddTwoNumbers { public static void main(String[] args) { System.out.println(“Addition of two numbers 10 + 20 is ” + (10 + 20)); } }
Output
We must understand this that, here numbers are added directly say 10 + 20 that is 30. But what we get numbers from console. In that case the values will be stored in a variable. In terms of Java, String array variable will store those numbers based on their index.
public class Main { public static void main(String[] args) { System.out.println("Addition of two numbers " + args[0] + " + " + args[1] + " is " + (args[0] + args[1])); } }
The output for this will be as shown in Console when we pass same number that is 10 and 20.
Eh, the result we got here is not desired 30. Remember String[] args, every input you take from console is represented in String. So here we have to convert those Strings into Integer to calculate the addition.
public class Main { public static void main(String[] args) { //System.out.println("Addition of two numbers " + args[0] + " + " + args[1] + " is " + (args[0] + args[1])); System.out.println("Addition of two numbers " + args[0] + " + " + args[1] + " is " + (Integer.parseInt(args[0]) + Integer.parseInt(args[1]))); } }
Output
Now the desired output is what we want. That is the addition of 10 and 20 is 30 after we parsed it from String to Integer.
Next in this article on Addition Of two Numbers In Java
Using Subtraction operator: We can use subtraction to add two numbers such that it will negate the negative value and come thus resulting into addition.
public class AddTwoNumbers { public static int add(int a, int b) { return a – (-b); } public static void main(String[] args) { System.out.println(add(10, 20)); System.out.println(add(-10, 20)); } }
Ouput
30
10
Next in this article on Addition Of two Numbers In Java
This involves while loop, the basic idea behind this is to bring the value of first operand to zero. And to keep on increamenting its corresponding second operand by the same amount of iterations. Consider the below example yourself.
public class HelloWorld { public static void main(String []args) { System.out.println("add " + add(10, 20)); System.out.println("add " + add(-10, 20)); } public static int add(int a, int b) { //System.out.println("---> " + a + " : " + b); while(a > 0) { //System.out.println("while a>0---> " + a + " : " + b); b++; a--; } while(a < 0) { //System.out.println("while a<0---> " + a + " : " + b); b--; a++; } //System.out.println("return b---> " + a + " : " + b); return b; } }
Ouput
$javac HelloWorld.java $java -Xmx128M -Xms16M HelloWorld add 30 add 10
Next in this article on Addition Of two Numbers In Java
We can also do the addition of two integers by using XOR bitwise operator and carry can be obtained by AND operator. To add carry into sum we need to use signed left shift operator. How does this happens? Let’s first see an example.
public class HelloWorld{ public static void main(String []args){ System.out.println("Addition using +ve " + addUsingBits(10, 20)); System.out.println("Addition using -ve " + addUsingBits(-10, 20)); } public static int addUsingBits (int a, int b){ while (b != 0){ int carry = (a & b); a = a ^ b; b = carry << 1; } return a; } }
Output
$javac HelloWorld.java
$java -Xmx128M -Xms16M HelloWorld
Addition using +ve 30
Addition using -ve 10
Always remember that, XOR operation is used to evaluate addition of two bits. AND operation is used to evaluate carry of two bits. Let’s dissect this shall we? Going by the input values let’s take a = 10 and b = 20 for first condition.
Operation | Expression evaluation | Binary equivalent | Decimal Value |
a | 10 | 00001010 | 10 |
b | 20 | 00010100 | 20 |
while(b != 0) | true | ||
int carry = (a & b) | 10 & 20 | 0 | 0 |
a = a ^ b | 10 ^ 20 | 00011110 | 30 |
b = carry << 1 | 0 << 1 | 0 | 0 |
return a | 30 | 00011110 | 30 |
Now, let’s take a negative input say -10 for a. Let’s examine what happens at the below table.This lets us in loop until the decimal value of carry comes to negative.
Next in this article on Addition Of two Numbers In Java
Operation | Expression evaluation | Binary equivalent | Decimal Value |
a | -10 | 11110110 | -10 |
b | 20 | 00010100 | 20 |
while(b != 0) | true | ||
int carry = (a & b) | -10 & 20 | 00010100 | 20 |
a = a ^ b | -10 ^ 20 | 11100010 | -30 |
b = carry << 1 | 20 << 1 | 00101000 | 40 |
Loop 1.
Operation | Expression evaluation | Binary equivalent | Decimal Value |
a | -30 | 11100010 | -30 |
b | 40 | 00101000 | 40 |
while(b != 0) | true | ||
int carry = (a & b) | -30 & 40 | 00100000 | 32 |
a = a ^ b | -30 ^ 40 | 11001010 | -54 |
b = carry << 1 | 32 << 1 | 00101000 | 64 |
And so on… until loop turns out to be b=0; for brevity not all result is shown here. So below table represents last loop in this operation.
Operation | Expression evaluation | Binary equivalent | Decimal Value |
a | -2147483638 | 1111111111111111111111111111111110000000000000000000000000001010 | -2147483638 |
b | -2147483648 | 1111111111111111111111111111111110000000000000000000000000000000 | -2147483648 |
while(b != 0) | true | ||
int carry = (a & b) | -2147483638 & -2147483648 | 1111111111111111111111111111111110000000000000000000000000000000 | -2147483648 |
a = a ^ b | -2147483638 ^ -2147483648 | 00001010 | 10 |
b = carry << 1 | -2147483648 << 1 | 0 | 0 |
return a | 10 | 00001010 | 10 |
So that’s how the addition got calculated. Phew! so much for the thought. Just think if this calculation was done manually by humans, mainly binary calculations.
Next in this article on Addition Of two Numbers In Java
We can also write the above program using recursion too. The calculation part differs slightly lets consider this for homework for you shall we? I will give the extract here for the recursion and you try to build your own table so that you know how it works internally. Also, no need to mug all this that is only for representation purpose unless you are excited about internal workings here.
public static int addUsingRecursion(int a, int b){ if(b == 0) return a; int sum = a ^ b; int carry = (a & b) << 1; return add(sum, carry); }
This was all for the addition of two numbers in Java with using + operator and without using + operator. The reason behind going for either of those will entirely depend on the project need and requirement.
I have not evaluated and tested the working of both the scenario to come up with performance. I guess that will come into effect only if you are building the rocket and deliver it to space.
I have explained only numbers related to Integers for brevity which has its own memory limit. I leave it to you to further explore using float, double, etc. Always remember that if you exceed the limit value of primitive types then the result will show different answer.
Check out the Java Certification Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming your best, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer.