Simple Calculator program in Java

Simple Calculator program in Java

Java allows us to perform basic arithmetic operations such as addition, multiplication, division, subtraction, etc. We can write separate programs to perform all the operations separately or we can write a single program which will perform all the arithmetic operations. To perform arithmetic operations we will require arithmetic operators. Arithmetic operators in Java are +, -, *, /, %. So let’s see the program for simple calculator in java.

Code-

import java.util.Scanner;
class Calculator
{
  public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
	System.out.println("Enter 2 numbers: ");
	int x=sc.nextInt();
	int y=sc.nextInt();
	System.out.println("1.Addition\n2.Subtraction\n3.Multiplication\n4.Quotient\n5.Remainder");
	int n=sc.nextInt();
	switch(n)
	{
		case 1:System.out.println("Addition = "+(x+y));
			break;
		case 2:System.out.println("Subtraction = "+(x-y));
			break;
		case 3:System.out.println("Multiplication = "+(x*y));
			break;
		case 4:System.out.println("Quotient = "+(x/y));
			break;
		case 5:System.out.println("Remainder = "+(x%y));
			break;
		default:System.out.println("Invalid input!");
			break;
	}
  }
}

Output-

calculator program java output

Explanation

The program will accept 2 numbers. It is simply going to perform arithmetic operations on the entered values. It will display a list of operations to choose. Then the entered choice will be checked using switch statement. And the corresponding steps will be done.

Program parts-

  1. class– Used to declare a class in java.
  2. public– Access modifier which represents it is visible to all.
  3. static– The main method is declared as static, so it doesn’t require to create an object to invoke the main method.
  4. void– Return type of the method.
  5. main– Represents the starting point of the program.
  6. Scanner– Scanner is a class in java. util package used for obtaining the input.
  7. String[] args– Used for command line argument.
  8. System.out.println()– System is a class, out is the object of PrintStream class, println() is the method of PrintStream class. System.out.println is used to print a statement.
  9. System.in is an InputStream.

Conclusion-

So this was the simple Calculator program in java. We hope it was clear to you. If you have doubt regarding any concept or this post just mention it in the comments. For daily updates and more such content do follow us on Instagram.

Keep programming!

ErrorFreeProgram.

Leave a Reply

Your email address will not be published. Required fields are marked *