top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Arithmetic Operators in Java

Introduction

Arithmetic operators in Java are indispensable for performing mathematical operations. They allow you to add, subtract, multiply, divide, and perform many other mathematical operations. To execute mathematical calculations and manipulate numeric values in Java programs, it is essential to understand arithmetic operators.

Overview

In this tutorial, we will learn about arithmetic operators in Java. They are used to perform basic mathematical operations in Java. This tutorial also covers the different types of arithmetic operators and their uses with the help of examples. 

Types of Operators

Java has several types of operators, each with a distinct function. The most common Java operators are discussed below:

Unary Operators

The unary operator in Java is an operator that can only be used in conjunction with an operand. It is employed to denote a positive or negative value, an increment or a decrement of one, and the complement of a Boolean value.

Unary operators can be classified into two types: prefix and postfix operators.

Prefix Unary Operators:

Increment: ++operand (increments the value of the operand by 1)

Decrement: --operand (decrements the value of the operand by 1)

Unary Plus: +operand (returns the value of the operand)

Unary Minus: -operand (negates the value of the operand)

Postfix Unary Operators:

Increment: operand++ (increments the value of the operand by 1 and returns the original value)

Decrement: operand-- (decrements the value of the operand by 1 and returns the original value)

Assignment Operator

To assign a value to a variable in Java, we use the assignment operator (=) in Java. It gives the variable on the left side of the operator the value that is on the right side of the operator. 

Example:

int a = 5;

int b = a;

Relational Operators

Relational operators are used in Java to compare values and establish their relationship. Based on the comparison outcome, these operators yield a boolean value, either true or false.

There are 6 types of relational operators used in Java. They are:

  • Equal to (==): This operator checks if both operands are equal.

Example:

int a = 10;

int b = 5;

boolean c = a == b;

  • Not equal to (!=):  This operator checks if two operands are unequal. It is a boolean type operator and returns ‘true’ only when both operands are unequal.

Example:

int a = 11;

int b = 12;

boolean c = a != b;

  • Greater than (>): This operator is used to check if the value of one variable is more than the other. This boolean type operator returns ‘true’ if an operand is greater than the comparing operand.

Example:

int a = 32;

int b = 6;

boolean c = a > b;

  • Less than (<): This operator is used to check if the value of one variable is less than another variable. This boolean type operator returns ‘true’ if an operand is lesser in value than the comparing operand.

Example:

int a = 8;

int b = 89;

boolean c = a < b;

  • Greater than or equal to (>=): This operator checks if a variable is greater than or equal to another variable. This boolean type operator returns ‘true’ if the value of a variable is greater than or equal to the comparing variable.

Example:

int a = 22;

int b = 9;

boolean c = a >= b; 

  • Less than or equal to (<=): This operator checks if a variable is lesser than or equal to another variable. This boolean type operator returns ‘true’ if the value of a variable is lesser than or equal to the comparing variable.

Example:

int a = 6;

int b = 12;

boolean c = a <= b;

Logical Operators

Logical operations on boolean expressions or values are performed in Java using logical operators. These operators let you mix different circumstances and assess the outcome. 

There are three logical operators in Java. They are

  • Logical AND (&&): Only returns ‘true’ when both the criteria are true

Example:

boolean variable1 = true;

boolean variable2 = true;

boolean outcome = variable1 && variable2;

  • Logical OR (||): Returns ‘true’ when either one of the operands is true, or both are ‘true’.

Example:

boolean variable3 = false;

boolean variable4 = true;

boolean outcome = variable3 || variable4;

  • Logical NOT (!): Reverses the value of the operand and returns it.

Example:

boolean variable5 = true;

boolean outcome = !variable5;

Ternary Operators

The conditional operator, also called the ternary operator in Java, is a convenient way to create conditional statements. It enables you to select one of two expressions to analyze and choose depending on a condition. 

Syntax:

Condition ? expression1 : expression2

Example: 

Int age = 60;
String result = (age >= 59) ? “Senior” : “Junior”;

Bitwise Operators

Bitwise operators are used in Java to carry out operations on a single bit of an integer value. These operators change the bits that make up the binary representation of integers.

There are four types of bitwise operators in Java. They are:

  • Bitwise AND (&): Performs a bitwise AND operation on the corresponding bits of two operands. The result has a 1 bit in each position where both operands have a 1 bit.

Syntax: operand1 & operand2

  • Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation on the corresponding bits of two operands. The result has a 1 bit in each position where only one of the operands has a 1 bit.

Syntax: operand1 ^ operand2

  • Bitwise NOT (~): Performs a bitwise NOT (complement) operation on the operand, which flips all the bits, turning 0s into 1s and 1s into 0s.

Syntax: ~operand

  • Bitwise OR (|): Performs a bitwise OR operation on the corresponding bits of two operands. The result has a 1 bit in each position where at least one of the operands has a 1 bit.

Syntax: operand1 | operand2

Shift Operators

Shift operators in Java are bitwise operations that move a value's bits to the left or right. The shift operators allow you to shift the bits of an integer left or right. There are three types of shift operators in Java:

  • Left shift operator (<<)

  • Right shift operator (>>)

  • Unsigned right shift operator (>>>)

Arithmetic Operators

There are broadly five types of arithmetic operators in Java. Here, we will further discuss them in detail with the help of examples.

Addition(+) Operator

The addition operator (+) in Java is an arithmetic operator that adds numerical operands. It is mainly employed for two-number addition. Any numeric type, such as int, double, float, long, short, or byte, may be used for the operands. The addition operator adheres to the standard addition arithmetic rules.

Example:

public class AdditionOperatorExample {
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 20;
        int sum = num1 + num2;
        System.out.println("Sum: " + sum);
    }
}

In this example, we have initialized two integer variables, num1, and num2, with the values 10 and 20, respectively. The addition operator + adds the values of num1 and num2, and the result is stored in the sum variable.

Finally, the value of sum is printed using System.out.println().

Subtraction(-) Operator

The arithmetic operator for subtracting from numeric operands in Java is the subtraction operator (-). The subtraction operator follows the standard arithmetic rules for subtraction. The second operand is subtracted from the first operand. Any type of numeric data, including int, double, float, long, short, and byte, may be used as the operands.

Example:

public class main {
    public static void main(String[] args) {
        int num1 = 30;
        int num2 = 10;
        int difference = num1 - num2;
        System.out.println("Difference: " + difference);
    }
}

In this example, we have two integer variables, num1, and num2, initialized with the values 30 and 10, respectively. The subtraction operator - is used to subtract the value of num2 from num1, and the result is stored in the difference variable.

Finally, the value of difference is printed using System.out.println().

Multiplication(*) Operator

The multiplication operator (*) in Java is an arithmetic operator used to multiply numerical operands. It is applied when multiplying two numbers together. Any numeric type, such as int, double, float, long, short, or byte, may be used for the operands. The multiplication operator adheres to the common multiplication principles of arithmetic.

Example:

public class main {
    public static void main(String[] args) {
        int num1 = 5;
        int num2 = 6;
        int product = num1 * num2;
        System.out.println("Product: " + product);
    }
}

In this example, we have two integer variables, num1, and num2, initialized with the values 5 and 6, respectively. The multiplication operator * is used to multiply the values of num1 and num2, and the result is stored in the product variable.

Finally, the value of product is printed using System.out.println().

Division(/) Operation

The division operator (/) is an arithmetic operator in Java that divides numerical operands. It is employed to divide two numbers by two. Any type of numeric data, including int, double, float, long, short, and byte, may be used as the operands. The division operator adheres to the standard divisional arithmetic rules.

Example:

public class main {
    public static void main(String[] args) {
        int dividend = 20;
        int divisor = 5;
        int quotient = dividend / divisor;
        System.out.println("Quotient: " + quotient);
    }
}

In this example, we have two integer variables, dividend, and divisor, initialized with the values 20 and 5, respectively. The division operator / divides the dividend by the divisor, and the result is stored in the quotient variable.

Finally, the value of the quotient is printed using System.out.println().

Modulus(%) Operation

The modulus operator (%) in Java is an arithmetic operator used to determine the remainder after dividing two numbers. The modulus operator adheres to the accepted arithmetic principles when calculating the remainder. Any type of numeric data, including int, double, float, long, short, and byte, may be used as the operands.

Example:

public class ModulusOperatorExample {
    public static void main(String[] args) {
        int dividend = 20;
        int divisor = 6;
        int remainder = dividend % divisor;
        System.out.println("Remainder: " + remainder);
    }
}

In this example, we have two integer variables, dividend, and divisor, initialized with the values 20 and 6, respectively. The modulus operator % is used to find the remainder when the dividend is divided by the divisor, and the result is stored in the remainder variable.

Finally, the value of remainder is printed using System.out.println().

Conclusion

Java arithmetic operators allow you to work with numerical quantities in mathematical calculations. You can modify numbers in your programs using their addition, subtraction, multiplication, division, and modulus operators.

You can build robust algorithms and incorporate complicated logic in your Java programs by combining arithmetic operators with other operators, such as relational, logical, and assignment operators.

Checking out courses from upGrad is an excellent way to learn more about core Java concepts in depth.

FAQs

1. What distinguishes the modulus (%) operator from the division (/) operator?

The modulus operator (%) returns the remainder of the division while the division operator (/) executes the division and returns the quotient.

2. What occurs in Java when you divide an integer by zero?

In Java, an ArithmeticException error is raised when an integer is divided by zero. Due to the ambiguity of division by zero, it is not permitted.

3. How can I divide using a decimal result rather than an integer result?

Floating-point numbers can be used to divide a number into a decimal result. For instance, you may cast one of the operands to a floating-point type or split two doubles.

Leave a Reply

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