Let us now see an example of a java program to add two integers.
In this program, user is asked to enter two integers. Then, the sum of those two integers is stored in a variable and displayed on the screen.
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values.
Step 4: Add num1 and num2 and assign the result to sum.
Step 5: Display sum
Step 6: Stop
public static void main(String args)
int num1; //Declare variables
System.out.println("\n \n *** www.programmingposts.com *** \n \n"); //prints on the output device
System.out.println("<< JAVA Program to Add Two Integers >> \n \n")
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first number to be added:");
num1 = scanner.nextInt();
System.out.println("Enter the second number to be added:");
num2 = scanner.nextInt();
result = num1+num2; //adds the values of num1 and num2 and stores the result in the variable result.
System.out.println("Addition of two numbers is " +result); // prints the value of result on output device.
import java.util.Scanner– it imports util package into the code which contains Scanner class in it.
class Addition– The class declaration component declares the name of the class.
public static void main(String args) – Java starts running a program with this specific signature
public- is an Access Modifier, which defines who can access this Method. Public means that this Method will be accessible by any Class.
static- is a keyword which identifies the class related thing. This means the given Method or variable is not instance related but Class related.It can be accessed without creating the instance of a Class.
void- is used to define the Return Type of the Method. Void means the Method will not return any value.
main- is the name of the Method. This Method name is searched by JVM as a starting point for an application with a particular signature only. String args : is the parameter to the main Method.
Scanner scanner = new Scanner(System.in)– Scanner class allows the user to read values of various types. new creates a java object and allocates memory for it in heap. System.in is an input stream.
scanner.nextInt() – Scans the next token of the input as an int
C:\Users\santo\Desktop\new>javac Addition.javaC:\Users\santo\Desktop\new>java Addition
*** www.programmingposts.com ***
<< JAVA Program to Add Two Integers >>
Enter the first number to be added:
Enter the second number to be added:
Addition of two numbers is 14
Screenshot of Output: