How to Make a Simple Calculator in Java (Using If-Else & Switch-Case) | Beginner Tutorial

Опубликовано: 12 Июль 2026
на канале: Raghav Maheshwari
401
6

Ready to build your first practical Java application? This tutorial will guide you step-by-step through creating a simple command-line calculator in Java. It's the perfect project for beginners to solidify their understanding of core programming concepts.

We will cover two different approaches to handle the logic, so you can see which one you prefer!

In this video, you will learn how to:

Accept user input (numbers and operators) using the Scanner class.

Perform basic arithmetic operations: Addition, Subtraction, Multiplication, and Division.

Control the program's logic using an if-else if-else statement.

Control the program's logic using a switch statement.

Handle potential errors, like division by zero.

Structure your code cleanly for a functional and readable program.

Whether you're a student just starting your coding journey or someone looking for a quick refresher, this tutorial will give you the confidence to build simple, interactive applications in Java.

💻 Find the complete source code on GitHub: [Link to your GitHub repository here]

🔔 If this video was helpful, please Like, Subscribe, and hit the notification bell for more easy-to-follow Java programming tutorials!

SWITCH CASE:--
import java.util.*;

public class CalculatorSwitch
{
public static void main(String []args)
{
Scanner first = new Scanner(System.in);
int d;
System.out.println("No1 PRESS ENTER");
int a = first.nextInt();
System.out.println("Enter 1 to +,2 to -,3 to *,4 to / PRESS ENTER");
int b = first.nextInt();
System.out.println("No2 PRESS ENTER");
int c = first.nextInt();
switch(b)
{
case 1 :
d = a+c;
System.out.println(d);
break;

case 2 :
d = a-c;
System.out.println(d);
break;

case 3 :
d = a*c;
System.out.println(d);
break;

case 4 :
d = a/c;
System.out.println(d);
break;

default :
System.out.println("invaild No");
}

}
}


IF-ELSE CASE:--

import java.util.*;

public class CalculatorIf
{
public static void main(String []args)
{
Scanner first = new Scanner(System.in);
int d;
System.out.println("No1 PRESS ENTER");
int a = first.nextInt();
System.out.println("Enter 1 to +,2 to -,3 to *,4 to / PRESS ENTER");
int b = first.nextInt();
System.out.println("No2 PRESS ENTER");
int c = first.nextInt();
if(b == 1)
{
d = a+c;
System.out.println(d);
}
else
{
if(b == 2)
{
d = a-c;
System.out.println(d);
}
else
{
if(b == 3)
{
d = a*c;
System.out.println(d);
}

else
{
if(b ==4)
{
d = a/b;
System.out.println(d);
}
else
{
System.out.println("Invalid");
}
}
}
}

}
}