The Wayback Machine - https://web.archive.org/web/20241008230911/https://www.geeksforgeeks.org/java-arithmetic-operators-with-examples/
Open In App

Java Arithmetic Operators with Examples

Last Updated : 28 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: 

  1. Arithmetic Operators
  2. Unary Operators
  3. Assignment Operator
  4. Relational Operators
  5. Logical Operators
  6. Ternary Operator
  7. Bitwise Operators
  8. Shift Operators

This article explains all that one needs to know regarding Arithmetic Operators. 

Arithmetic Operators

These operators involve the mathematical operators that can be used to perform various simple or advanced arithmetic operations on the primitive data types referred to as the operands. These operators consist of various unary and binary operators that can be applied on a single or two operands. Let’s look at the various operators that Java has to provide under the arithmetic operators. 

Arithmetic Operators in Java

Now let’s look at each one of the arithmetic operators in Java: 

1. Addition(+): This operator is a binary operator and is used to add two operands.

Syntax: 

num1 + num2

Example: 

num1 = 10, num2 = 20
sum = num1 + num2 = 30

Java




// Java code to illustrate Addition operator
 
import java.io.*;
 
class Addition {
    public static void main(String[] args)
    {
        // initializing variables
        int num1 = 10, num2 = 20, sum = 0;
 
        // Displaying num1 and num2
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
 
        // adding num1 and num2
        sum = num1 + num2;
        System.out.println("The sum = " + sum);
    }
}


Output

num1 = 10
num2 = 20
The sum = 30

2. Subtraction(-): This operator is a binary operator and is used to subtract two operands. 

Syntax: 

num1 - num2

Example: 

num1 = 20, num2 = 10
sub = num1 - num2 = 10

Java




// Java code to illustrate Subtraction operator
 
import java.io.*;
 
class Subtraction {
    public static void main(String[] args)
    {
        // initializing variables
        int num1 = 20, num2 = 10, sub = 0;
 
        // Displaying num1 and num2
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
 
        // subtracting num1 and num2
        sub = num1 - num2;
        System.out.println("Subtraction = " + sub);
    }
}


Output

num1 = 20
num2 = 10
Subtraction = 10

3. Multiplication(*): This operator is a binary operator and is used to multiply two operands. 

Syntax: 

num1 * num2

Example: 

num1 = 20, num2 = 10
mult = num1 * num2 = 200

Java




// Java code to illustrate Multiplication operator
 
import java.io.*;
 
class Multiplication {
    public static void main(String[] args)
    {
        // initializing variables
        int num1 = 20, num2 = 10, mult = 0;
 
        // Displaying num1 and num2
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
 
        // Multiplying num1 and num2
        mult = num1 * num2;
        System.out.println("Multiplication = " + mult);
    }
}


Output

num1 = 20
num2 = 10
Multiplication = 200

4. Division(/): This is a binary operator that is used to divide the first operand(dividend) by the second operand(divisor) and give the quotient as a result. 

Syntax: 

num1 / num2

Example: 

num1 = 20, num2 = 10
div = num1 / num2 = 2

Java




// Java code to illustrate Division operator
 
import java.io.*;
 
class Division {
    public static void main(String[] args)
    {
        // initializing variables
        int num1 = 20, num2 = 10, div = 0;
 
        // Displaying num1 and num2
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
 
        // Dividing num1 and num2
        div = num1 / num2;
        System.out.println("Division = " + div);
    }
}


Output

num1 = 20
num2 = 10
Division = 2

5. Modulus(%): This is a binary operator that is used to return the remainder when the first operand(dividend) is divided by the second operand(divisor). 

Syntax: 

num1 % num2

Example: 

num1 = 5, num2 = 2
mod = num1 % num2 = 1

Java




// Java code to illustrate Modulus operator
 
import java.io.*;
 
class Modulus {
    public static void main(String[] args)
    {
        // initializing variables
        int num1 = 5, num2 = 2, mod = 0;
 
        // Displaying num1 and num2
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
 
        // Remaindering num1 and num2
        mod = num1 % num2;
        System.out.println("Remainder = " + mod);
    }
}


Output

num1 = 5
num2 = 2
Remainder = 1

Here is an example program in Java that implements all basic arithmetic operators for user input:

Java




import java.util.Scanner;
 
public class ArithmeticOperators {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        System.out.print("Enter the first number: ");
        double num1 = sc.nextDouble();
 
        System.out.print("Enter the second number: ");
        double num2 = sc.nextDouble();
 
        double sum = num1 + num2;
        double difference = num1 - num2;
        double product = num1 * num2;
        double quotient = num1 / num2;
 
        System.out.println("The sum of the two numbers is: " + sum);
        System.out.println("The difference of the two numbers is: " + difference);
        System.out.println("The product of the two numbers is: " + product);
        System.out.println("The quotient of the two numbers is: " + quotient);
    }
}


Input

Enter the first number: 20
Enter the second number: 10

Output

The sum of the two numbers is: 30.0
The difference of the two numbers is: 10.0
The product of the two numbers is: 200.0
The quotient of the two numbers is: 2.0

Explanation 

  • The program implements basic arithmetic operations using user input in Java. The program uses the Scanner class from the java.util package to read user input from the console. The following steps describe how the program works in detail:
  • Import the java.util.Scanner class: The program starts by importing the Scanner class, which is used to read input from the console.
  • Create a Scanner object: Next, a Scanner object sc is created and associated with the standard input stream System.in.
  • Read the first number from the user: The program prompts the user to enter the first number and uses the nextDouble() method of the Scanner class to read the input. The input is stored in the num1 variable of type double.
  • Read the second number from the user: The program prompts the user to enter the second number and uses the nextDouble() method of the Scanner class to read the input. The input is stored in the num2 variable of type double.
  • Perform arithmetic operations: The program performs the four basic arithmetic operations (addition, subtraction, multiplication, and division) using the num1 and num2 variables and stores the results in separate variables sum, difference, product, and quotient.
  • Print the results: The program prints out the results of the arithmetic operations using the println method of the System.out object.
  • This program demonstrates how to implement basic arithmetic operations using user input in Java. The Scanner class makes it easy to read user input from the console, and the basic arithmetic operations are performed using standard mathematical operators in Java.


Previous Article
Next Article

Similar Reads

Java Relational Operators with Examples
Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Types of Operators: Arithmetic OperatorsU
10 min read
Short Circuit Logical Operators in Java with Examples
In Java logical operators, if the evaluation of a logical expression exits in between before complete evaluation, then it is known as Short-circuit. A short circuit happens because the result is clear even before the complete evaluation of the expression, and the result is returned. Short circuit evaluation avoids unnecessary work and leads to effi
3 min read
Java Assignment Operators with Examples
Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Types of Operators: Arithmetic OperatorsU
7 min read
Java Logical Operators with Examples
Logical operators are used to perform logical "AND", "OR" and "NOT" operations, i.e. the function similar to AND gate and OR gate in digital electronics. They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under particular consideration. One thing to keep in mind is, while using AND
10 min read
Java | Operators | Question 1
Predict the output of following Java Program class Test { public static void main(String args[]) { int x = -4; System.out.println(x>>1); int y = 4; System.out.println(y>>1); } } (A) Compiler Error: Operator >> cannot be applied to negative numbers (B) -2 2 (C) 2 2 (D) 0 2 Answer: (B) Explanation: See https://www.geeksforgeeks.org/
1 min read
Java | Operators | Question 2
Predict the output of following Java program. Assume that int is stored using 32 bits. class Test { public static void main(String args[]) { int x = -1; System.out.println(x>>>29); System.out.println(x>>>30); System.out.println(x>>>31); } } (A) 7 3 1 (B) 15 7 3 (C) 0 0 0 (D) 1 1 1 Answer: (A) Explanation: Please see https
1 min read
Java | Operators | Question 3
class Test { public static void main(String args[]) { System.out.println(10 + 20 + "GeeksQuiz"); System.out.println("GeeksQuiz" + 10 + 20); } } (A) 30GeeksQuiz GeeksQuiz30 (B) 1020GeeksQuiz GeeksQuiz1020 (C) 30GeeksQuiz GeeksQuiz1020 (D) 1020GeeksQuiz GeeksQuiz30 Answer: (C) Explanation: In the given expressions 10 + 20 + "Geeks
1 min read
Java | Operators | Question 4
class Test { public static void main(String args[]) { System.out.println(10*20 + "GeeksQuiz"); System.out.println("GeeksQuiz" + 10*20); } } (A) 10*20GeeksQuiz GeeksQuiz10*20 (B) 200GeeksQuiz GeeksQuiz200 (C) 200GeeksQuiz GeeksQuiz10*20 (D) 1020GeeksQuiz GeeksQuiz220 Answer: (B) Explanation: Precedence of * is more than +.Quiz of
1 min read
Java | Operators | Question 5
Which of the following is not an operator in Java? (A) instanceof (B) sizeof (C) new (D) >>>= Answer: (B) Explanation: There is no sizeof operator in Java. We generally don't need size of objects.Quiz of this Question
1 min read
Java | Operators | Question 6
class Base {} class Derived extends Base { public static void main(String args[]){ Base a = new Derived(); System.out.println(a instanceof Derived); } } (A) true (B) false Answer: (A) Explanation: The instanceof operator works even when the reference is of base class type.Quiz of this Question
1 min read
Java | Operators | Question 7
class Test { public static void main(String args[]) { String s1 = "geeksquiz"; String s2 = "geeksquiz"; System.out.println("s1 == s2 is:" + s1 == s2); } } (A) true (B) false (C) compiler error (D) throws an exception Answer: (B) Explanation: The output is “false” because in java + operator precedence is more than == op
1 min read
Java | Operators | Question 8
class demo { int a, b, c; demo(int a, int b, int c) { this.a = a; this.b = b; } demo() { a = b = c = 0; } demo operator+(const demo &obj) { demo object; object.a = this.a + obj.a; object.b = this.b + obj.b; object.c = this.c + obj.c; return object; } } class Test { public static void main(String[] args) { demo obj1 = new demo(1, 2, 3); demo obj
1 min read
Java | Operators | Question 9
Predict the output of the following program. Java Code class Test { boolean[] array = new boolean[3]; int count = 0; void set(boolean[] arr, int x) { arr[x] = true; count++; } void func() { if(array[0] && array[++count - 2] | array [count - 1]) count++; System.out.println("count = " + count); } public static void main(String[] args) { Test object =
1 min read
Bitwise Right Shift Operators in Java
In C/C++ there is only one right shift operator '>>' which should be used only for positive integers or unsigned integers. Use of the right shift operator for negative numbers is not recommended in C/C++, and when used for negative numbers, the output is compiler dependent. Unlike C++, Java supports following two right shift operators. Here w
2 min read
Basic Operators in Java
Java provides a rich operator environment. We can classify the basic operators in java in the following groups: Arithmetic OperatorsRelational OperatorsBitwise OperatorsAssignment OperatorsLogical Operators Let us now learn about each of these operators in detail. 1. Arithmetic Operators: Arithmetic operators are used to perform arithmetic/mathemat
10 min read
Compound assignment operators in Java
Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand. The following are all possible assignment operator in java: 1. += (compound addition assignment operator) 2. -= (compound subtraction a
7 min read
Interesting facts about Increment and Decrement operators in Java
Increment operator is used to increment a value by 1. There are two varieties of increment operator:  Post-Increment: Value is first used for computing the result and then incremented.Pre-Increment: Value is incremented first and then the result is computed.Example [GFGTABS] Java //INCREMENTAL OPERATOR //Let's see what exactly happens when we u
5 min read
Operators in Java
Java provides many types of operators which can be used according to the need. They are classified based on the functionality they provide. In this article, we will learn about Java Operators and learn all their types. What are the Java Operators?Operators in Java are the symbols used for performing specific operations in Java. Operators make tasks
15 min read
Bitwise Operators in Java
Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: Arithmetic Operator
6 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
RSA Algorithm using Multiple Precision Arithmetic Library
Public Key Cryptography is also known as Asymmetric Cryptography is the type of cryptography which involves the usage of two keys namely Public Key and Private Key. The Public Key of the receiver is used to encrypt the plaintext by the sender while the Private Key of the receiver is used to decrypt the encrypted message and hence can be decrypted o
4 min read
Large number arithmetic using doubly linked list
Given two very large numbers in form of strings. Your task is to apply different arithmetic operations on these strings. Prerequisite : Doubly Linked List. Examples: Input : m : 123456789123456789123456789123456789123456789123456789 n : 456789123456789123456789123456789123456789123456789 Output : Product : 563937184884934839205932493526930147847927
13 min read
Arithmetic instructions in 8086 microprocessor
Arithmetic Instructions are the instructions which perform basic arithmetic operations such as addition, subtraction and a few more. Unlike in 8085 microprocessor, in 8086 microprocessor the destination operand need not be the accumulator. Following is the table showing the list of arithmetic instructions: OPCODE OPERAND EXPLANATION EXAMPLE ADD D,
2 min read
Longest arithmetic progression that can be formed with the given common difference d
Given an unsorted array a[] of size n and an integer d which is the common difference, the task is to find the length of the longest AP that can be formed for all j, greater than some i(<n), if a[j] = a[i] + (j-i) * d i.e. a[j] is in the AP of a[i] from index i to j. Examples: Input: n = 6, d = 2 arr[] = {1, 2, 5, 7, 9, 85} Output: 4 The longest
7 min read
Character Arithmetic in C
As already known character range is between -128 to 127 or 0 to 255. This point has to be kept in mind while doing character arithmetic. What is Character Arithmetic?Character arithmetic is used to implement arithmetic operations like addition, subtraction, multiplication, and division on characters in C language. In character arithmetic character
2 min read
Largest in array without using conditionals / bitwise / ternary operators
Define a function int max(int a[], int n) which returns the largest integer from an integer array consisting of n elements (without using conditionals / bitwise / ternary operators / library function to find largest Examples: Input : arr[] = {16, 14, 15, 17, 9} Output : 17 Input : arr[] = {10, 13, 11, 13} Output : 13 The idea is similar to Maximum
4 min read
Go Operators
Operators are the foundation of any programming language. Thus the functionality of the Go language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In the Go language, operators Can be categorized based on their different functionality: Arithmetic OperatorsRelational OperatorsLogi
9 min read
Unary operators in C
Unary operators are the operators that perform operations on a single operand to produce a new value. Types of unary operatorsTypes of unary operators are mentioned below: Unary minus ( - )Increment ( ++ )Decrement ( -- )NOT ( ! )Addressof operator ( & )sizeof()1. Unary MinusThe minus operator ( - ) changes the sign of its argument. A positive
4 min read
Output of C programs | Set 58 (operators)
Prerequisite : Operators in C Q.1 What is the output of this program? #include <iostream> using namespace std; int main() { printf("value is = %d", (10 ++)); return 0; } Options a) 10 b) 11 c) compile time error d) run time error ans: c Explanation : lvalue required as increment operator operate only on variables and not constant va
3 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Article Tags :
Practice Tags :