Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to add two numbers.

Java Code Example — Basic Programs

ADVERTISEMENT

Java Program to add two numbers.

Objective

Write a Java program to add two numbers provided by the user.

Algorithm / Approach

  1. Import the Scanner class to take input.
  2. Prompt the user to enter two integers.
  3. Store the integers in variables x and y.
  4. Add the two numbers and store the result in z.
  5. 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 Scanner class to take input from the user.
  • It prompts the user to enter two integers, storing them in x and y.
  • The variable z is assigned the sum of x and y.
  • 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 of nextInt()).
ADVERTISEMENT