Basic Calculator Implemented in Java

import java.util.Scanner;

public class Calculator {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(;

    System.out.println("Enter first number:");
    double num1 = scanner.nextDouble();

    System.out.println("Enter second number:");
    double num2 = scanner.nextDouble();

    System.out.println("Enter an operator (+, -, *, /): ");
    String operator =;

    double result;
    switch (operator) {
      case "+":
        result = num1 + num2;
      case "-":
        result = num1 - num2;
      case "*":
        result = num1 * num2;
      case "/":
        if (num2 != 0) {
          result = num1 / num2;
        } else {
          System.out.println("Cannot divide by zero!");
        System.out.println("Invalid operator!");
    System.out.println("The result is: " + result);

In this example, the Scanner class is used to take input from the user. The program prompts the user to enter two numbers and an operator, and then performs the appropriate calculation based on the operator entered by the user.

The program uses a switch statement to evaluate the operator and to perform the corresponding calculation.

It also checks the second number for division operation if it’s not equal to zero if yes, it will return Cannot divide by zero! to the user.

This is a very simple example of a calculator. You can further enhance it to handle more complex operations and to improve error handling and input validation.