Operators In Java

Home /

Table of Contents

Operators in Java are symbols that are used to perform various operations on variables and values. There are several types of operators in Java, such as arithmetic operators, relational operators, logical operators, and assignment operators. Arithmetic operators include addition, subtraction, multiplication, division, and modulus. Relational operators are used to comparing two values, such as less than, greater than, equal to, and not equal to. Logical operators include AND, OR, and NOT, and are used to combine multiple conditions to form a single condition. Assignment operators are used to assigning a value to a variable, such as the equals sign (=) operator. Understanding how to use operators in Java is essential for developing complex programs that involve mathematical calculations and logical operations.

In our previous tutorial, we learned what variables are in java, and how to declare and initialize variables. In this tutorial, we will learn how to do something with them. A good place to start would be learning the operators of the Java Programming Language.

What Are Operators?

Operators are special symbols that perform specific operations on one, two or three operands, and then return a result. We use operators to perform operations on variables and values.

What Are Operands?

The value(s) or variable(s) we do an operation on is called the operand(s).

Example

Suppose we want to add two numbers. How do we perform this action in Mathematics?

20+25
xIF Hihv9QEv IJaZWV6DQSNRNq5 a7qm - Operators In Java
We are adding two numbers - 20 & 25. The operation is addition and is represented by the symbol - +. We are doing the addition operation on values 20 & 25, hence they are operands. They are values the + operator is working on.

Again,

   int a;
   int b;

Here we have declared two variables. We can do addition operations on integers as they are numbers.

 a + b

Here, the + symbol is the operator representing an addition operation, and variables a and b are operands.

kYf4VGhXD2lojTWG9dpJWKhdmRTlJ3qJIaZrtuFnbyIZJicSdMAnkzqM6MxLNh - Operators In Java
An expression is a combination of operators and operands. If you have done any basic algebra then most parts of this tutorial will be familiar to you.

What is The Precedence of the Operator?

Before moving further, it may be helpful for you to know ahead of time which operators have the highest precedence. The order in which operands are grouped with operators is defined by operator precedence. For example, the multiplication operator takes precedence over the addition operator, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3. Parentheses can be used to override the default operator precedence rules. Operators with higher precedence are evaluated before operators with relatively lower precedence.

Look at the following expression.

7 + 5 * 2

If we add 7 and 5 first and then multiply the result with 2 :

First Addition : 7 + 5 = 12
Now multiplication: 12 * 2= 24
The final result is 24.

If we multiply 7 and 5 first and then add the result to 2 :

     First multiplication :  5 * 2 = 10
     Now addition: 10 + 7 = 17
     The final result is 17.
The right answer is 17 as multiplication takes precedence over addition, the multiplication is done first and then the addition.

The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated from right to left.

IDSbguClTmUCAd05NeRdmlkxWkZWLXr5YPcC8RC5Uvty2rYtZvPMTIwcQs0QmF0IDoLTL97HhGQmnbRnOL4CB - Operators In Java

Certain operators appear more frequently than others in general-purpose programming; for example, the assignment operator “=” appears far more frequently than the unsigned right shift operator “>>>.” With that in mind, the discussion that follows begins with the operators that you’re most likely to use on a regular basis and ends with those that are less common. Each section includes sample code that you can compile and run. Examining its output will help you remember what you’ve just learned.

Assignment, Arithmetic, and Unary Operators

In Java, operators are symbols used to perform specific operations on one or more operands. There are several types of operators, including assignment, arithmetic, and unary operators. Assignment operators are used to assigning values to variables, such as the “=” operator. Arithmetic operators are used to performing mathematical operations, such as addition, subtraction, multiplication, and division.

Unary operators are used to performing operations on a single operand, such as negation or incrementation. Understanding how to use these operators is essential when developing programs in Java, as they can be used to perform a wide range of operations and calculations. It is important to note that operators in Java have a specific order of precedence, meaning that some operators are evaluated before others, which can affect the outcome of calculations.

The Simple Assignment Operator

We have already seen the Assignment Operator in action. Actually, this is one of the most common operators you’ll ever come across. This operator is represented by the symbol =. You encountered this operator while we were discussing variable initialization :

 int num = 23;

The assignment operator assigns the value on its right to the operand on its left.

The Arithmetic Operators

Java has five defined arithmetic operators.

FZGiuDNDuy10T7PE8NPGuyO MjMeFxQQ7Ti6ZSUlN9FW6KZcJpzd7xjJWTLPlRs7LEfnvPObXRdOkCUTWihMAaUKHkJk5fIME2U BAoTD4nPNED5Q - Operators In Java

You may recognize the symbols from their counterparts in mathematics. The modulus operator represented by % may be new to you. The 4 basic operators perform the basic addition, subtraction, multiplication, and division operation. The +, -, /, and * operators may be used with any of the primitive data types that represent numbers. However, the % may be used with integer types only. The modulus operator produces the remainder of an integer division. This has no meaning when applied to floating-point types.

The – operator has two meanings depending on the operation performed. Mainly it is the subtraction operator. It can be used to reverse the sign of a number as a unary minus. A unary operator uses only one operand.

Example

5 means positive number 5. If we put a unary minus sign before it then it becomes negative 5 : -5. But if we have at least two operands then it is a subtraction operator : 7 - 5.

From the table, we can see that the *, /, and % operators have higher precedence than the + and the –

However, using the parentheses we can alter the order of evaluation.

Example

This following expression produces the value zero.

10 - 2 * 5

But this one produces the value of 40.

(10 - 2) * 5

A java arithmetic expression may contain variables, constants, or both.

Example

Assuming that answer and count are variables, this expression is perfectly valid

int count = 200;
int answer = count - 100;

We are going to give you some test code here to play with the arithmetic expression.

public class ArithmeticOperatorDemo{

    public static void main(String[] args) {

        int result = 1 + 2;
        System.out.println("1 + 2 =" + result);

        result = 2 - 1;
        System.out.println("2 - 1 =" + result);

        result = 2 * 1;
        System.out.println("2 * 1 =" + result);

        result = 2 / 1;
        System.out.println("2 / 1 =" + result);

    }

}

Output

1 + 2 = 3
2 - 1 = 1
2 * 1 = 2
2 / 1 = 2

In this example performing calculations using arithmetic expressions, we have done the 4 basic arithmetic calculations: addition, subtraction, multiplication, and division.

In line 5 we have declared an int-type variable result to hold our answer in the memory. Then we performed an additional operation: 1+2 and the result of the operation is assigned to the variable result. Here we have done three operations:

Variable Declaration : int result;
Addition Operation: 1 + 2
Variable initialization and Assignment Operation: int result = 1 + 2;

In line 6 we have printed the result in the console using System.out.println();

In line 8 we have performed the following operations:

Subtraction Operation : 2 - 1
Assignment Operation: result = 2 - 1;

In line 9 we have printed the result in the console using System.out.println();

In line 11 we have performed the following operations:

Multiplication Operation : 2 * 1
Assignment Operation: result = 2 * 1

In line 12 we have printed the result in the console using System.out.println();

In line 14 we have performed the following operations:

Division Operation : 2 / 1
Assignment Operation: result = 2 / 1

In line 15 we have printed the result in the console using System.out.println();

Look at the example carefully. We have only declared one variable in this program. Then we initialized the variable in line 5 by storing the added value in the variable. In lines 8, 11, and 14 we have used the variable to store the result of subtraction, multiplication, and division. The key point to take from this is that we can use a variable to assign value as many times as we want. But if we assign a new value to the variable then the previously assigned value is completely replaced by the newly assigned value.  

Y3PwEW8ApxardylNdVY6YBKOEiIB2Sfcynhl3IASXrwr D2OckiOw0hvFVV2j0SbFKd4YQQgeFG3J4QuXLp6NP3smiRa4Fj3uEIvnHyBNsB0kr9lUQ0cG3miZyH1 D N5dl0cJKuWK0Vefm85A - Operators In Java

As stated earlier, the modulus operation returns the remainder of an integer division and the symbol used for this operation is %.

Example

The remainder of 10 % 3 equals 1.

The following java program shows the outcome of some integer divisions and their remainders.

public class RemainderDemo{

     public static void main(String[] args) {

        int result = 5 % 2;
        System.out.println(result);

        result = 4 % 2;
        System.out.println(result);

        result = 10 % 7;
        System.out.println(result);

    }

}

Output

1
0
3

This program is self-explanatory, so we will not bother to explain more. If you have any confusion regarding this program read the explanation of the ArithmeticOperatorDemo.

When we are calculating long expressions, we may use parentheses and spaces to add clarity, even if they are not necessary.

Example

Expression 1 : count * num+88 / val - 19 % count;
Expression 2 : (count * num) + (88 / val) - (19 % count);

Both expressions produce the same result. You can check it by creating a java application and using some random values for count, num, and value. But the 2nd expression is much easier to read.

The following java program computes the area of a rectangle, given its dimensions, and displays the area in the console.

public class RectangleArea{
    public static void main(String[] args) {
        int length = 25;
        int width = 9;
        int area = length * width;

        System.out.println("Area is : " + area);

    }
}

Output

Area is : 225

There is another use of the + operator. It can join two strings together. Joining two or more strings together to create a single new string is called string concatenation. 

Example

This program joins(concates) stringOne and stringTwo to create the new concatenated string  “This is a concatenated string.”, which gets printed to standard output.

public class StringConcatDemo{
    public static void main(String[] args){
        String stringOne = "This is";
        String stringTwo = " a concatenated string.";
        String finalString = stringOne + stringTwo;

        System.out.println(finalString);
    }
}

Output

This is a concatenated string

One final thing. Combining Arithmetic Operators with simple assignment operators to create compound assignments is an efficient method to perform calculations.

Example

        x+=1;
and     x=x+1;

 both increment the value of x by 1.

The Unary Operators

We have stated earlier that they – can be used as a unary operator to reverse the sign of its operand. The following program demonstrates how it works.

public class UnaryOperatorDemo{
    public static void main(String[] args) {

       int i=0;
       i=10;
       i=-1;

      System.out.println("This is i : " + i);
    }
}

Output

This is i : -10

The unary operators operate on only one operand. They perform various operations such as:

  •     incrementing/decrementing a value by one negating an expression
  •     inverting the value of a boolean.

The following table lists the Unary Operators.

a8fb8KA0QDib33shMoYdEA9GzTFaKVA4yrHY5s46BotXbcniG2eKjiPaa - Operators In Java

The following program demonstrates unary Operators.

public class UnaryOperatorDemo{
    public static void main(String[] args) {

        int result = +1;
        System.out.println(result);

        result--;
        System.out.println(result);

        result++;
        System.out.println(result);

        result = -result;
        System.out.println(result);

        boolean success = false;
        System.out.println(success);
        System.out.println(!success);
    }
}

Output

1
0
1
-1
false
true

In this example, we have used the unary operator to indicate a positive value, negate an expression, increment a value by 1, decrement a value by 1, and invert the value of a boolean.

In line 4 we have declared an int-type variable result to hold our answer in the memory. Then we indicated a positive value and the result of the operation is assigned to the variable result.

Here we have done three operations:

Variable Declaration : int result;
Positive Indication Operation: +1
Variable initialization and Assignment Operation: int result = +1;

In line 5 we have printed the result in the console using System.out.println();

In line 7 we have performed the following operation:

Decrement Operation : result--;

In line 8 we have printed the result in the console using System.out.println();

In line 10 we have performed the following operation:

Increment Operation : result++;

In line 11 we have printed the result in the console using System.out.println();

In line 13 we have performed the following operation:

Negation Operation : -result;
Assignment Operation: result = -result;

In line 14 we have printed the result in the console using System.out.println();

In line 16 we have performed the following operations:

Variable Declaration : boolean success;
Variable initialization and Assignment Operation: boolean success = false;

In line 17 we have printed the result in the console using System.out.println();

In line 18 we have inverted the value of success and printed the result in the console using System.out.println();

One key point to take from this tutorial is that we can use increment/decrement operators before(prefix) or after(postfix) the operand. In our example: result++ and ++result will both increment the result by one. There is a difference though. The prefix version(++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.
public class PrePostDemo {
    public static void main(String[] args){
        int i = 3;
        i++;
        System.out.println(i);

        ++i;
        System.out.println(i);

        System.out.println(++i);

        System.out.println(i++);
 
        System.out.println(i);
    }
}

Output:

4
5
6
6
7

Try to figure out the result of this PrePostDemo program. We will explain the program when we discuss comments.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.

Other Recommended Article