Java Program to Add Two Numbers

0

In this tutorial we will learn how to add two numbers and print the result. We will try two program to add the numbers. In the first program, we just add two numbers and print the sum. The second program user is asked to enter two numbers using Scanner class and sum the numbers.

Java program to add two numbers without using Scanner


public class Main
{
public static void main(String[] args) {
int number1 = 10, number2 = 20, sum;
sum = number1 + number2; // Adding two number and sum will be result
//Display result
System.out.println("Sum of number1 and number2: "+sum);
}
}


Output:


Sum of number1 and number2: 30


Java program to add two numbers using Scanner

The Scanner class provides the methods that allows us to read the user input. The values entered by user is read using Scanner class and stored in two variables number1 and number2. The program then calculates the sum of input numbers and displays it.


import java.util.Scanner;

public class Main
{
public static void main(String[] args) {
int number1, number2, sum;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first number");
number1 = scanner.nextInt();
System.out.println("Enter the Second number");
number2 = scanner.nextInt();
scanner.close();
sum = number1 + number2; // Adding two number and sum will be result
//Display result
System.out.println("Sum of number1 and number2: "+sum);
}
}

In this program we created Scanner scanner = new Scanner(System.in); This is the line which create Scanner class object and accept the user input and store into the number1 and number2 variables.Once the values are stored in variables. The addition is performed on these variables and result is displayed.

Output:


Enter the first number
10
Enter the Second number
20
Sum of number1 and number2: 30


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !