- Java Programming Examples
- 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
- Java Check Leap Year or Not
- Check Reverse equal Original
- Add Subtract Multiply & Divide
- Java Make Calculator
- Java Add Digits of Number
- 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
- Calculate Area & Perimeter
- Calculate Area & Circumference
- Java Fahrenheit to Celsius
- Java Celsius to Fahrenheit
- Java Print ASCII Values
- Java Print Fibonacci Series
- Java Check Palindrome or Not
- Java Check Armstrong or Not
- Generate Armstrong Numbers
- Java Find nCr nPr
- 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 Print Diamond Pattern
- Java Print Floyd Triangle
- Java Print Pascal Triangle
- One Dimensional Array Program
- Java Linear Search
- Java Binary Search
- Add two Numbers using Pointers
- 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
- Two Dimensional Array Program
- Java Add two Matrices
- Java Subtract two Matrices
- Java Transpose Matrix
- Multiply two Matrices
- Three Dimension Array Program
- 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
- Generate Random Numbers
- Java Read File
- Java Write to File
- Read & Display File Content
- Java Copy File
- Java Merge two File
- List files in Directory
- Java Delete File
- Java Print Time & Date
- Java Get IP Address
- Java Shutdown Computer
- Java Binary Number Addition
- Java Append Text to File
- Java Discount Program
- Java Compute Courier Charge
- Java Find Simple Interest
- Java Find Telephone Bill
- Java Check Balance Parentheses
- Java Check Divisibility
- Java Check Password Strength
- Java Perfect Number Program
- Java Find Quotient Remainder
- Java Find Common Elements
- Java Days to Seconds
- Java Count Even/Odd Number
- Java Count Digits in Number
- Java Find Compound Interest
- Java Programming Tutorial
- Java Tutorial
- Java Interview Questions
- Java Interview Questions
- Java Programming Test
- Java Programming Test
- Give Online Test
- All Test List

« Previous Program Next Program »

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.

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 CodesCracker { 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:

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 CodesCracker { 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:

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 CodesCracker { 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 **codescracker** as first number:

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 CodesCracker { 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.

« Previous Program Next Program »

© Copyright 2021. All Rights Reserved.