How to Write a Java Program to Add Two Numbers
We are going to learn how to write a java program to add two numbers which is probably the easiest program ever. Remember the time when we didn’t know anything about calculators? Yeah, me neither. I think I have always used them the moment I ran out of fingers.
So, let’s assume there are big hefty numbers at play and we are too lethargic to calculate them manually, or use a calculator because it’s kept in the other side of the room, also all other applications on our system are not working. In short a highly unlikely scenario, and we have Java with us. Well, good news Ramanujan! We can add stuff by using Java!
So, without wasting any more time let’s learn how to write a java program to add two numbers. We will see how to subtract them too. Then we will learn how to wrap everything beautifully under the aegis of methods. Yes, it’s all in here.
How to Write a Java Program to Add Two Numbers
I have really had it up with notepads. I am going to switch over to using an IDE. If you have never heard about it before I advise you to learn all about Eclipse IDE and how to install it before proceeding here.
From this point onwards, in the impending chapters I am going to stick strictly to learning with Eclipse. Because, I want to get a hang of it. Also, it’s a good practice and it’s cool.
So!
In order learn how to write a Java program to add two numbers you gotta create a workspace first in Eclipse. Here’s a step by step explanation of how to do that, and how to get started with Eclipse.
Getting all Warmed Up
Remember I am going to create everything from scratch here so if you are having doubts on how to go about Eclipse, just come back to this page and understand how to create Project, Package and Class.
Step 1: Create a new Java Project.
Clicking on a Java Project is going to a dialog box that would ask you to enter a project name. Just do what it says. I am going to name my project as RedForman. Yeah! I am a big “That 70s Show” fan.
Click on Finish and it will set you up.
Step 2: Add a package to your project since you want things to be organized. Right click on your Project name, here RedForman and then on New > Package.
Click on Finish once you are done.
Notice how the package name goes under the aegis of src? Well src is nothing but your source code folder. If you manually navigate to the folder you will actually see kitty named folder inside the src folder.
How to create a Class in Eclipse
Step 3: Now it is time to create a new class. In a similar manner right-click on the package (here kitty) and navigate to New> Class.
Notice there’s a checkbox that says “public static void main(String[] args)”. If you check that flag you are going to have a class that will already have the above main method written.
Go ahead and check that. Enter a class name in the Name field and then click on Finish.
I am going to name my class as “Eric”. Yes the coolest character from the show.
Once you click on Finish you might get something like this:
Notice the public static main method is already there. You didn’t have to write anything.
Cool! Right?
Saves you a lot of time. Told ya!
Using Comments
We are going to write our code in the main method and try to execute it in Eclipse IDE itself. So delete everything that’s inside the method or you can leave it since ‘//’ is used for commenting. Everything that follows the symbol “//” are ignored by JVM. It is used for adding a comment to tell other readers about what’s what in your code.
// is used for commenting in a single line. In case you want to use a multi-line commenting system make use of ‘/*’. Eclipse will automatically close your comments with ‘*/’.
Okay, moving on.
Addition Program in Java
To add two numbers we need two numbers. You don’t have to be a Rocket Scientist to know that.
We are going to create two variables that will hold the numbers. Remember what you had learnt about data types? If you do, then you are going to walk right through it without realizing it was a big deal.
Step 4: Let’s create two variables namely a and b and initialize them with some numbers that need adding.
int a = 5; int b = 4;
I know what you are thinking right now. Adding 5 and 4? Pfft…Like that’s tough! Feel free to use huge numbers in place of a and b. I will stick at some puny Maths.
Notice how we have used the data type as int? Int stands for integer meaning ‘a’ is supposed to hold an integer. So if you are using anything other than an integer in place of 5 it is going to show an error.
Step 5: Now that we have declared them, we need a place to cash in our result in. So let’s create another field called sum and mark it as int too.
Whatever operation needs to be performed should direct to sum. So writing the following code:
int sum = a + b;
is going to tell JVM what needs to be done.
Here is a glimpse of how things appear in our code:
Now that wouldn’t suffice. It has simply put the result in sum variable. Hasn’t it?
How do we show it?
Yes, you guessed right, we need to display the “sum” variable. Displaying stuff is generally done by using System.out.print command if you remember your past lessons in Java.
Step 6: Append your code with the
System.out.println(sum);
command and save.
Run the Program
Step 7: When you are done all you need to do is run the program. To do that Eclipse provides a shortcut button. Here’s where you can find it, that little green play button:
You can alternatively right click on the blank empty area and select Run As…Java program too.
When you run the program you will get the result in the Console located in the bottom area.
There! That’s your result right there?
Did you know what 5 and 4 were going to fetch you? Oh, you are the cool kid now?
Downcasting Issues
An interesting example in how to write a java program to add two numbers is when casting issues come.
Bringing the knowledge of Primitive Data Types here and seeing if we use int with float.
int a = 5; double b = 4.5; int sum = a + b;
If we try to run the above we will get an error. Since, int is a lower category. The alternative to that is either make “sum” as double (upcasting)
double sum = a + b;
or use downcasting by making the code look like:
int sum = (int) a + b;
Which is also fine but when you try to run each one of the above you will get two different results namely:
9.5 9
Hence, we can say that downcasting isn’t good for our code. We can establish the following rule with the above example:
- Downcasting makes us lose data.
- Using upcasting you can save data.
How to Write a Java Program to Add Two Numbers Using Objects and Methods
Now since we have already worked on Classes, Objects and Methods before, we are going to do the same thing a tad differently. What say? You in?
We will see how to write a Java program to add two numbers by using methods hereby.
Alright, so like how all good codes should be written, let’s create a different method altogether called sum().
Step 1: Delete everything you put in the main method just now, or create a new class whatever suits you. Make sure your main method isn’t brimming with words now. So things should get back to their normal look when you have just created a new class:
Step 2: Create a new method called sum(). Put it outside the main method so that we are going to call it using an object. Make sure you define or declare everything inside the “sum” method.
Step 3: Now we are going to call the sum method from main. To do that we need to create an object. How do we do that?
Following the syntax of creating the object we use the Class name and create an object called obj.
Now that doesn’t actually do anything but create an object instance of Eric class. Now we gotta call sum method using this object and the (.) dot operator.
Step 4: Append the following code and we are done:
obj.sum();
The above will help in calling the sum method. Here’s how the final code should look like:
Step 5: Go ahead and run the program. You shall get the following:
Return Keyword
Notice how we have chosen void as the return type for sum()? Void means it returns nothing. If we wish to use the sum result that we have retrieved from the method somewhere in our code in main, that wouldn’t work if we simply choose to display ‘c’.
To use that method’s result we need to change our return type to something that allows us to return something. That means losing the return type as void. You can replace it with ‘int’. Using int as the return type means you gotta make use of the return keyword.
Simply replace void with int and add return in place of System.out.println code.
Now we can use whatever has been returned from sum() in our main method without any issues. Go ahead and display whatever has returned using System.out command. Make sure you assign obj.sum() to an int variable like I have done below:
Once you are done run the program. You will get the same result.
Better?
How to Write a Java Program to Add Two Numbers Using Parameters in Java
Notice how we have been manually putting nay…hard-coding numbers like 5 and 4 assigning them to a and b? Supposedly there is a code change, and we are asked to use different numbers, what would happen then? Changing the numbers would be a Herculean task when we are talking about hundreds of numbers.
To avoid that we can make use of Parameters in methods. Yes, there’s a better way on how to write a java program to add two numbers using parameters.
To do that simply change the code to:
int sum(int x, int y)
Understanding Parameter Usage
I know the first thing that might confuse you is why the brackets have been braced with int x and int y suddenly. This is how we call a method. We can put as many variables as we want separated by commas like this:
int sum(int x, int y, int z, ........int n)
And in order to call this method we have to write the following in the main method:
obj.sum(1,2,3,............66)
You get the gist right?
Then you need to assign x and y to the variables that you are using inside the method. Remove the numbers and assign x and y to a and b.
int a = x;
int b = y;
Well, it means whatever we use in place of x and y while calling the method, it is going to be treated as a and b, and the same logic goes on to treat these variables
Now in order to call this method sum(x,y) we need to simply use the number in the brackets that are like a mirror image to our portal.
Go ahead and run the program. Getting 9 again? Cool right?
Now change the numbers from (5, 4) to (545645, 6756756)
What do you get?
Using this type of coding is top-notch, since you can keep your methods intact this way, and only mess with the main function.
Taking Inputs as you Please
Now I know what you are thinking. After learning how to write a Java Program to add two numbers what if we wish to use our own numbers?
What if you wish to manually enter numbers at run time? Those numbers could be any number in your head. That’s where Scanner class comes into picture. We are going to learn all about taking inputs in a different chapter.
Also, you could use Java GUI or AWT to make an interesting looking program. I have created an addition program using GUI here.
But Hobo! Aren’t we tired? Oh yes! I am.
We are going to learn all about taking inputs at run time in a different chapter. Till then Adios!
3 Responses
[…] the previous chapter, we had learnt all about how to add two numbers that were already there with you. What if the user […]
[…] If you are confused about the working of parameters you can go back to the chapter that teaches how parameters work in Java. […]
[…] that program we did to add two numbers? We are going to simply uptrade! We will create a Java GUI program to add two numbers using AWT and […]