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.*;
public 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:
public class AddTwo
: Any Java program starts with a class, in this case the class name is AddTwopublic static void main(String[] args)
: main is the entry point for any Java program.int a, b;
: Declare variables a and b of type integerScanner 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).System.out.print("Enter the value of a:\t");
: Prompts the user to enter the value of a.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.System.out.print("Enter the value of b:\t");
: Prompts the user to enter the value of b.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.int sum = a + b;
: Calculate the sum of a and b and store it in variable sum.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