Write a Java program to input two numbers add two numbers. In this example we will learn to use arithmetic operator to find sum of two numbers. We will learn to input two number from user and find sum of two numbers in Java.
Example
Input
Input
First number: 10 Second number: 5
Output
Sum of 10 and 5 is : 15
Required knowledge
Basic input/output, Arithmetic operator
This example does not require any special Java knowledge. You just need to know how to read input from user.
Program to add two numbers and print result
/**
* Java program to add two numbers and print result.
*/
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
// Create scanner class object
Scanner in = new Scanner(System.in);
// Input two numbers from user
System.out.print("Enter first number : ");
int num1 = in.nextInt();
System.out.print("Enter second number : ");
int num2 = in.nextInt();
// Calculate addition of both numbers
int result = num1 + num2;
// Print result
System.out.println("Sum of " + num1 + " and " + num2 + " is : " + result);
}
}
Note: We use
System.out.println()
to print string on console and move to next line. WhereasSystem.out.print()
print string and stays in the same line.
Output
Enter first number : 10 Enter second number : 5 Sum of 10 and 5 is : 15
Happy coding 😉