Simple Calculator Program in Java

Baruni Priya T S
2 min readJun 10, 2021

Overview

In this blog, we will develop a simple calculator in Java programming language that can perform basic operations like addition, subtraction, multiplication, division, finding remainder and exponentiation. These operations are performed by using a switch case statement in Java.

Photo by Karolina Grabowska from Pexels

Program Description

The program should input two numerical values from the user. The program must ask the user what is the operation to be performed with the given values. According to the user’s choice, the arithmetic operation is performed and the output will be displayed on the console. Also, the user is asked whether to continue the program execution. If yes, the program execution starts again. Otherwise, the program ends.

How It Works

  1. Get two numerical values from the user.
  2. Also, get the operation to be performed. (+, -, *, /, %, ^)
  3. Pass the operator value as an argument to the switch case statement.
  4. When the operator value matches any one of the case conditions, the statements under that case is executed.
  5. The result is calculated and displayed on the console.
  6. If the operator value doesn’t match any of the case conditions, then the default block is executed which prints a message that the choice is incorrect.
  7. After the result is displayed, the user is asked to continue. If yes, the above statements are executed again. Else, the execution ends.

To execute the above statements repeatedly, they are put under a while loop with an initial condition of choice == ‘y’. When the user says to end the program, the choice becomes no(i.e. choice == ‘n’). Hence the program stops the execution.

Source Code

Here is the source code of a simple calculator in Java.

Output

Are you looking to master coding and crack top company interviews? Go ahead and try GUVI’s Pro Subscription to help you with everything needed to build a strong Technical Career.

Know more about GUVI:

Also, download GUVI’s app to learn the latest IT skills in vernacular languages.

--

--