Addition Of Two Numbers In Java
In this article, I am going to introduce you to a simple yet important concept that is the addition of two numbers in Java. But before moving ahead, I would suggest you get familiar with “What is Java”, the features of Java and how can you install Java on your system. 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,
- Method 1
- Method 2
- Repeated Unary Operator
- Initial Loop Table
- Bitwise And Bitshift Operator In Java
- Recursion
So let us get started then,
Addition of two numbers in Java
Method 1
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));
}
}
We must understand that here numbers are added directly say 10 + 20 that is 30. But what we get numbers from the console. In that case, the values will be stored in a variable. In terms of Java, the 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 the 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 the 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
Method 2
- 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));
}
}
Output
30
10
Next in this article on the Addition Of two Numbers In Java
Repeated Unary Operator
This involves a while loop, the basic idea behind this is to bring the value of the first operand to zero. And to keep on incrementing 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 the Addition Of two Numbers In Java
Bitwise And Bitshift Operator 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 happen? 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 the addition of two bits. AND operation is used to evaluate the carry of two bits. Let’s dissect this, shall we? Going by the input values let’s take a = 10 and b = 20 for the first condition.
Now, let’s take a negative input say -10 for a. Let’s examine what happens at the below table. This lets us in a loop until the decimal value of carrying comes to negative.
Next in this article on the Addition Of two Numbers In Java
Initial Loop Table
Loop 1.
And so on… until loop turns out to be b=0; for brevity not all result is shown here. So below table represents the last loop in this operation.
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 the Addition Of two Numbers In Java
Recursion
We can also write the above program using recursion too. The calculation part differs slightly let's 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 purposes 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 the + operator and without using the + operator. The reason behind going for either of those will entirely depend on the project's need and requirements. 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 a float, double, etc. Always remember that if you exceed the limit value of primitive types then the result will show a different answer.
If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, Python, Ethical Hacking, then you can refer to Edureka’s official site.
Do look out for other articles in this series that will explain the various other aspects of Java.
1. Object Oriented Programming
5. Java String
6. Java Array
8. Java Threads
9. Introduction to Java Servlets
11. Exception Handling in Java
12. Java Tutorial
14. Java Programs
15. Kotlin vs Java
16. Dependency Injection Using Spring Boot
22. Socket Programming In Java
25. Library Management System Project in Java
26. Trees in Java
28. Top Data Structures & Algorithms in Java
30. Top 55 Servlet Interview Questions
34. Java Collections Interview Questions and Answers
35. How to Handle Deadlock in Java?
36. Top 50 Java Collections Interview Questions You Need to Know
37. What is the concept of String Pool in Java?
38. What is the difference between C, C++, and Java?
39. Palindrome in Java- How to check a number or string?
40. Top MVC Interview Questions and Answers You Need to Know
41. Top 10 Applications of Java Programming Language
42. Deadlock in Java
43. Square and Square Root in Java
Originally published at https://www.edureka.co on September 19, 2019.