Monday, 21 September 2015

Addition of Two numbers in Java

     Addition of two numbers is a basic program like hello world in JAVA.
There are several methods used to add two numbers in JAVA.
The very basic concept used to add two numbers was given below:-
class add
public static void main(String args[])
int a=10;
int b=20;
int c;
System.out.println(“Addition of two numbers=”+c);

Program Explanation

In this program the first line “import*” is the header file (contains package name) that provides the related classes and methods for executing the program.
A class name can be explicitly specified in place of “*”.
Then the class name is “add’.
Inside the class main method is defined. Inside the method Integer variables are declared and values are assigned (int a=10, int b=20).
Another Integer variable is declared to store the result value.
Then in the operation part using “+” operator Addition operation is performed and the result is stored in “c”.
Finally the result is displayed from the variable c using the statement “System.out.println(“Addition of two numbers=”+c);”


In this statement System is a predefined class and out is the static member of the system class and println is the method of print stream class.
Anything mentioned between double quotes inside this System.out.println will displayed in the output screen.
If we want to print the value of any variable that was mentioned after the “+” from double quotes. For example see the above highlighted code.
In this statement the first letter S must be in Uppercase.  
Because JAVA is a case sensitive language and the predefined classes (Like System, String etc.) in JAVA classes must be start with uppercase.
Then compile the program and execute it.
That’s it we have done. We have successfully added two numbers in JAVA.

No comments :

Post a Comment