Java Program to find sum of two integer numbers using Scanner Class

In this program let us create a Java program to print the sum of two numbers on the console by taking user inputs.

Program

import java.util.*;
class AddTwo
{
	public static void main(String args[])
	{
		int a, b;
		Scanner sc = new Scanner(System.in);
		System.out.print("Enter the value of a:\t");
		a = sc.nextInt();
		System.out.print("Enter the value of b:\t");
		b = sc.nextInt();
		int sum = a + b;
		System.out.println("Sum: \t" + sum);
	}
}

Let us understand the program by breaking into simple parts:

  1. public class AddTwo: Any Java program starts with a class, in this case the class name is AddTwo
  2. public static void main(String[] args): main is the entry point for any Java program.
  3. int a, b; : Declare variables a and b of type integer
  4. Scanner sc = new Scanner(System.in); : System.in is passed as a parameter in Scanner class. This creates an object of Scanner class which is defined in java. util. scanner package. Scanner class tells the java compiler that system input will be provided through console(keyboard).
  5. System.out.print("Enter the value of a:\t"); : Prompts the user to enter the value of a.
  6. a = sc.nextInt(); : The nextInt() method of Java Scanner class is used to scan the next token of the input as an int. The value of n entered by the user is stored in the variable a.
  7. System.out.print("Enter the value of b:\t"); : Prompts the user to enter the value of b.
  8. b = sc.nextInt(); : The nextInt() method of Java Scanner class is used to scan the next token of the input as an int. The value of n entered by the user is stored in the variable b.
  9. int sum = a + b; : Calculate the sum of a and b and store it in variable sum.
  10. System.out.println("Sum: \t" + sum);: System.out.println prints the value of sum with user entered inputs.

Output

Enter the value of a:	56
Enter the value of b:	19
Sum: 	75

Tags: