Java Program to add two numbers.
Objective
Write a Java program to add two numbers provided by the user.
Algorithm / Approach
- Import the
Scannerclass to take input. - Prompt the user to enter two integers.
- Store the integers in variables
xandy. - Add the two numbers and store the result in
z. - Print the value of
z.
Demo.java
import java.util.Scanner;
class Demo {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Num1: ");
int x = s.nextInt();
System.out.print("Enter Num2: ");
int y = s.nextInt();
int z = x+y;
System.out.println("Sum = "+z);
}
}
Expected Output
Enter Num1: 5 Enter Num2: 6 Sum = 11
Explanation of the Program
- The program uses the
Scannerclass to take input from the user. - It prompts the user to enter two integers, storing them in
xandy. - The variable
zis assigned the sum ofxandy. - Finally, it prints the result using
System.out.println().
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Forgetting to import
java.util.Scanner. - Using the wrong scanner method (e.g.,
nextLine()instead ofnextInt()).