- Java Basic Programs
- Java Programming Examples
- Java Print Hello World
- Java Get Input from User
- Java Print Integer
- Java Add two Numbers
- Java Check Even or Odd
- Java Check Prime or Not
- Java Check Alphabet or Not
- Java Check Vowel or Not
- Check Reverse equal Original
- Java Fahrenheit to Celsius
- Java Celsius to Fahrenheit
- Java Perfect Number Program
- Java Find Quotient Remainder
- Java Days to Seconds
- Java Count Digits in Number
- Java Binary Number Addition
- Java Discount Program
- Java Compute Courier Charge
- Java Find Telephone Bill
- Java Print ASCII Values
- Java Check Palindrome or Not
- Java Check Armstrong or Not
- Generate Armstrong Numbers
- Add two Numbers using Pointers
- Java Mathematical Programs
- Add Subtract Multiply & Divide
- Java Make Calculator
- Java Add Digits of Number
- Java Check Leap Year or Not
- Java Check Divisibility
- Java Find Simple Interest
- Java Find Compound Interest
- Java Print Fibonacci Series
- Java Find nCr nPr
- Calculate Average & Percentage
- Java Calculate Arithmetic Mean
- Java Calculate Student Grade
- Java Print Table of Number
- Java Print Prime Numbers
- Java Add n Numbers
- Java Interchange two Numbers
- Java Reverse Numbers
- Java Swap two Numbers
- Count Positive Negative & Zero
- Find Largest of two Numbers
- Find Largest of three Numbers
- Java Find Factorial of Number
- Java Find HCF & LCM
- Area & Perimeter of Square
- Area & Perimeter of Rectangle
- Area & Circumference of Circle
- Java Conversion Programs
- Java Decimal to Binary
- Java Decimal to Octal
- Java Decimal to Hexadecimal
- Java Binary to Decimal
- Java Binary to Octal
- Java Binary to Hexadecimal
- Java Octal to Decimal
- Java Octal to Binary
- Java Octal to Hexadecimal
- Java Hexadecimal to Decimal
- Java Hexadecimal to Binary
- Java Hexadecimal to Octal
- Java Pattern Programs
- Java Pattern of Stars
- Java Pattern of Alphabets
- Java Pattern of Numbers
- Java Pyramid of Stars
- Java Pyramid of Alphabets
- Java Pyramid of Numbers
- Java Print Diamond Pattern
- Java Print Floyd Triangle
- Java Print Pascal Triangle
- Java Array Programs
- One Dimensional Array Program
- Java Linear Search
- Java Binary Search
- Find Largest Element in Array
- Find Smallest Element in Array
- Java Reverse Array
- Insert Element in Array
- Delete Element from Array
- Java Merge two Array
- Java Bubble Sort
- Java Selection Sort
- Java Insertion Sort
- Java Find Common Elements
- Java Count Even/Odd Number
- Two Dimensional Array Program
- Java Add two Matrices
- Java Subtract two Matrices
- Java Transpose Matrix
- Multiply two Matrices
- Three Dimension Array Program
- Java String Programs
- Java Print String
- Find Length of String
- Java Compare two String
- Java Copy String
- Java Concatenate String
- Java Reverse String
- Delete Vowels from String
- Delete Words from Sentence
- Find Occurrence of a Character
- Java Find Occurrence of a Word
- Occurrence of Each Character
- Java Occurrence of Each Word
- Java Count Repeated Characters
- Java Count Repeated Words
- Java Capitalize Each Word
- Java Count Vowels/Consonants
- Java Extract Numbers
- Java Count Word in String
- Remove Spaces from String
- Java Sort a String
- Java Uppercase to Lowercase
- Java Lowercase to Uppercase
- Java Swap two Strings
- Java Check Anagram or Not
- Java Check Balance Parentheses
- Java Check Password Strength
- Java File Programs
- Java Read File
- Java Write to File
- Read & Display File Content
- Java Copy File
- Java Append Text to File
- Java Merge two File
- List files in Directory
- Java Delete File
- Java Miscellaneous Programs
- Generate Random Numbers
- Java Print Time & Date
- Java Get IP Address
- Java Shutdown Computer
- Java Programming Tutorial
- Java Tutorial
Java Program for Addition, Subtraction, Multiplication and Division
In this example, you'll get to learn, how to perform addition, subtraction, multiplication, and division of any two numbers in Java. Before starting the actual program, let's first create a very simple program that performs four basic mathematical operations without user input.
Addition, Subtraction, Multiplication, Division without User Input
The question is, write a Java program that performs four basic mathematical operations such as addition, subtraction, multiplication, and division. Here is its answer. I've not allowed user to feed the input for this program, but later on, this program is modified to allow user to provide the input at run-time of the program to perform operation of two desired numbers.
public class fresherearth { public static void main(String[] args) { int num1 = 20, num2 = 15, res; res = num1 + num2; System.out.println("Addition Result = " + res); res = num1 - num2; System.out.println("Subtraction Result = " + res); res = num1 * num2; System.out.println("Multiplication Result = " + res); res = num1 / num2; System.out.println("Division Result = " + res); } }
The output produced by this Java program will exactly be:
Addition, Subtraction, Multiplication, and Division with User Input
This program is basically the modified version of previous program, as it allows user to enter numbers for the program. Rest of the things are similar to previous program.
import java.util.Scanner; public class fresherearth { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int num1, num2, res; System.out.println("Enter the First Number: "); num1 = scan.nextInt(); System.out.println("Enter the Second Number: "); num2 = scan.nextInt(); res = num1 + num2; System.out.println("\nAddition Result = " + res); res = num1 - num2; System.out.println("Subtraction Result = " + res); res = num1 * num2; System.out.println("Multiplication Result = " + res); res = num1 / num2; System.out.println("Division Result = " + res); } }
Here is its sample run with user input 44 as first and 23 as second number:
Basic Mathematical Operation in Java - Complete Version
This is the complete version of the above program, as it handles errors too. Because, sometime user enters wrong or invalid inputs like c or # in place of number. Therefore, the program must be created in a way to handle those type of errors.
import java.util.Scanner; import java.util.InputMismatchException; public class fresherearth { public static void main(String[] args) { Scanner scan = new Scanner(System.in); double num1, num2, res; System.out.println("Enter the First Number: "); try { num1 = scan.nextDouble(); } catch(InputMismatchException e) { System.out.println("\nInvalid Input!"); System.out.println("Exception Name: " + e); return; } System.out.println("Enter the Second Number: "); try { num2 = scan.nextDouble(); } catch(InputMismatchException e) { System.out.println("\nInvalid Input!"); System.out.println("Exception Name: " + e); return; } res = num1 + num2; System.out.println("\nAddition Result = " + res); res = num1 - num2; System.out.println("Subtraction Result = " + res); res = num1 * num2; System.out.println("Multiplication Result = " + res); res = num1 / num2; System.out.println("Division Result = " + res); } }
Here is its sample run with user input 32 as first and 31 as second number:
Here is another sample run with an invalid user input as second number say 32 as first, but c as second number:
If you enter any invalid input as first number, then the program prints error message say Invalid Input! along with exception name. Also the second number will not get received from user, by the program, because I've used return keyword to stop the remaining execution of the program, when user feed an invalid input. For example, let's take another sample run with user input fresherearth as first number:
Add, Subtract, Multiply, Divide based on User's Choice
This is the minimal version of the above program, as it performs only single desired operation at a time, based on user's choice.
import java.util.Scanner; public class fresherearth { public static void main(String[] args) { Scanner scan = new Scanner(System.in); float num1, num2, res; char ch; System.out.println("Enter any Two Numbers: "); num1 = scan.nextFloat(); num2 = scan.nextFloat(); System.out.println("Enter the Operator (+, -, *, /): "); ch = scan.next().charAt(0); if(ch == '+') res = num1 + num2; else if(ch == '-') res = num1 - num2; else if(ch == '*') res = num1 * num2; else if(ch == '/') res = num1 / num2; else { System.out.println("\nInvalid Input"); return; } System.out.println("\nResult = " + res); } }
Here is its sample run with user input 10 and 30 as first and second number, and + as operator to perform the addition of these two numbers only:
The above program uses if...else if...else conditional statements to check and perform the operation based on the operator entered by user.
Same Program in Other Languages
« Previous Program Next Program »