This is our second program. It will input two numbers from the user and display their sum on the screen.

Problem:
Input two numbers from the user and display their sum on the screen.

Code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
 /**
  * @author Hafiz Muhammad Umer
  */
 import java.util.Scanner;
 public class Sum 
 {
     public static void main(String[] args) 
     {
         Scanner input=new Scanner(System.in);
         int a,b,sum;
         System.out.print("Enter the first number: ");
         a=input.nextInt();
         System.out.print("Enter the second number: ");
         b=input.nextInt();
         sum=a+b;
         System.out.println("The sum of "+a+" and "+b+" is "+sum);
     }
 }
Output:
Enter the first number: 2
Enter the second number: 3
The sum of 2 and 3 is 5
Explanation:
  • The line 4 imports the Scanner utility in java. It will be used to create Scanner objects so that we can take input in our program.
  • Line 5 defines a class which ends at line 18.
  • Line 7 defines the main method which ends at line 17.
  • Line 9 creates a Scanner object named input.
  • Line 10 defines three int variables.
  • From line 11 to 14, two values are taken from the user as input.
  • At line 15, the sum of a and b is stored in the variable sum.
  • At line 16, the sum is displayed on the screen.