Learn Java from Scratch: Operators in Java10 min read

In the previous article, we’ve talked about variables and data types. We already learned what is a variable, and how many data types that Java supports. In this article, we will learn about operators in Java and use those operators to work and manipulate with variables.

What is the operator?

An operator in a Java, like other programming languages, is a symbol that tells the compiler or interpreter to perform a specific mathematical, relational or logical operations and produce a final result. And usually, an operator is a character that carries out an action, such as adding, multiplying, subtracting, etc…

Types of operators in Java

Java provides a rich set of operators to use in manipulating variables. A value used on either side of an operator is called an operand. Types of operators in Java include:

  • Arithmetic operators
  • Assignment operators
  • Logical operators
  • Equality and Relational operators
  • Unary operators
  • Bitwise operators
  • Tenery operators

We will talk a closer look at all of the types we have listed above right underneath.

Arithmetic operators

There are some basic arithmetic operators in Java which are adding ( + ), substracting ( – ), multiplying ( * ), dividing ( / ) and modulo ( % ) which returns a remainder. For example:

 class ArithmeticOperators {
    public static void main(String[] args){
        int a = 10, b = 5, result;
        // Addition operator
        result = a + b;
        System.out.println("a + b = " + result);
        // Substraction operator
        result = a - b;
        System.out.println("a - b = " + result);
        // Multiplication operator
        result = a * b;
        System.out.println("a * b = " + result);
        // Division operator
        result = a / b;
        System.out.println("a / b = " + result);
        // Modulo operator
        result = a % b;
        System.out.println("a % b = " + result);
    }
} 

When you run this program, the output will be like this:

a + b = 15
a - b = 5
a * b = 50
a / b = 2
a % b = 0

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebraic equations.

Assignment Operators

Assignment operators in Java are used to assign values to variables, which assigns the value on its right to the variable on its left. For instance:

int age;
age = 18;

Here the value 18 is assigned to age by using = operator.

There are some assignment operators in Java which are +=, -=, *=, /=, %=. And those operators are shorthand for:

int a = 5, b = 7
a += b; which is equivalent to a = a + b
a -= b; which is equivalent to a = a – b
a *= b; which is equivalent to a = a * b
a /= b; which is equivalent to a = a / b
a %= b; which is equivalent to a = a % b

Look at the code segment below:

 class AssignmentOperators{
    public static void main(String[] args){
        int a, b;
        a = 20;
        b = 15;
        System.out.println("a = " + a + ", b = " + b);

        a += b;
        System.out.println("a += b output is: " + a);

        a -= b;
        System.out.println("a -= b output is: " + a);

        a *= b;
        System.out.println("a *= b output is: " + a);

        a /= b;
        System.out.println("a /= b output is: " + a);

        a %= b;
        System.out.println("a %= b output is: " + a);

    }
} 

And the output of this code fragment will be:

a = 20, b = 15
a += b output is: 35
a -= b output is: 20
a *= b output is: 300
a /= b output is: 20
a %= b output is: 5

Logical Operators

Logical operators are mainly used in looping and conditional statements (which we will examine later), the result of logical operators are either true or false.

The logical operators || (conditional-OR), and && (conditional-AND). For example:

a && b will return true if a is true AND b is true.
a || b will return true if either a OR b is true or both are true.

Look at the following code below:

 class LogicalOperators{
    public static void main(String[] args){
        boolean a = false;
        boolean b = true;
        boolean result;

        result = a && b;
        System.out.println("a && b :" + result);

        result = a || b;
        System.out.println("a || b :" + result);
    }
} 

After running this code:

a && b :false
a || b :true

The && and || operators “short-circuit”, meaning they don’t evaluate the right-hand side if it isn’t necessary. For instance:

 class ShortCircuitOperator{
    public static void main(String[] args){
        boolean a = false;
        boolean b = true;
        boolean c = true;

        // Because a is false and we perform AND operator, the output will be false and 'b && c' will not be necessarily evaluated.
        System.out.println("a && b && c: " + (a && b && c));

        // Because b is true and we perform OR operator, and the output will be true and (b && c) will not be evaluated.
        System.out.println("b || (a && c): " + (b || (a && c)));
    }
} 

Output:

a && b :false
a || b :true

Equality and Relational Operators

Equality and relational operators determine the relationship between the two operands. It checks if an operand is greater than, less than, equal to, not equal to and so on. Likewise in Logical operators, the result of equality and relational operators are either true or false. Look at the table below for more detail:

OperatorDescriptionExample
==returns true if the left and the right side are equal5 == 4 // false
!=returns true if the left and the right side are not equal5 != 4 // true
>returns true if the left side is greater than the right side5 > 4 // true
<returns true if the left side is less than the right side 5 < 4 // false
>=returns true if the left side is greater than or equal to the right side5 >= 4 // true
<=returns true if the left side is less than or equal to the right side 5 <= 4 // false

Look at the code fragment below:

 class EqualityAndRelationalOperators{
    public static void main(String[] args){
        int a = 5, b =7;
        
        System.out.println("a > b: " + (a > b));

        System.out.println("a < b: " + (a < b));

        System.out.println("a >= b: " + (a >= b));

        System.out.println("a <= b: " + (a <= b));

        System.out.println("a == b: " + (a == b));
    }
} 

And the output when we run this program will be:

a > b: false
a < b: true
a >= b: false
a <= b: true
a == b: false

Unary Operators

Unary operators are operators that perform on only one operand.

OperatorMeaning
+Unary plus (not necessary to use since numbers are positive without using it)
Unary minus; inverts the sign of an expression
++Increment operator; increments value by 1
Decrement operator; decrements value by 1
!Logical complement operator; inverts the value of a boolean, true becomes false and vice versa

For example:

 class UnaryOperators{
    public static void main(String[] args){
        int a = 5; 
        boolean isThisTrue = true;
        
        System.out.println("+a :" + (+a));

        System.out.println("-a :" + (-a));

        System.out.println("a++ :" + (++a));

        System.out.println("a-- :" + (--a));

        System.out.println("!isThisTrue :" + (!isThisTrue));
    }
} 

Output:

+a :5
-a :-5
a++ :6
a-- :5
!isThisTrue :false

A gentle note about increment/decrement operators, each of them has two forms, prefix, and postfix. With prefix form, the operator appears before the operand, while in postfix form, the operator appears after the operand. With prefix increment/decrement, the value will be increased/decreased by 1 before assigning to a variable. While with postfix increment/decrement, the variable’s value is first used in the expression and is then increased/decreased. Examine an example below for better understanding:

 class PrefixAndPostfix{
    public static void main(String[] args){
        int x = 30;
        int y = ++x;
        System.out.println("The value of x is : " + x + ", the value of y is: " + y);

        int a = 20;
        int b = a++;
        System.out.println("The value of a is : " + a + ", the value of b is: " + b);
    }
} 

Output:

The value of x is : 31, the value of y is: 31
The value of a is : 21, the value of b is: 20

As you can see, with the prefix form, the value will be increased by 1 after applied to the = operator, thus x = 31 and y = 31 also. But with postfix form, the initial value of a will be assigned to b, which is 20, then after that the value of a will be increased by 1, hence, a is 21 and b is 20.

Bitwise Operators

The number in Java is usually in decimal, but when working with bitwise operators, the value will be converted to binary (base 2) and perform the bit-by-bit operation. Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. First, let’s examine those operators on the table below:

Operator
Description
& (bitwise and)
Binary AND Operator copies a bit to the result if it exists in both operands.
| (bitwise or)
Binary OR Operator copies a bit if it exists in either operand.
^ (bitwise XOR)
Binary XOR Operator copies the bit if it is set in one operand but not both.
~ (bitwise compliment)
Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits.
<< (left shift)
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
>> (right shift)
Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
>>> (zero fill right shift)
Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.

For example, we have two variables which are a and b have values of 5 and 7 respectively and we will carry out some bitwise operators with them:

The value of 5 in binary is: 101
The value of 7 in binary is: 111
——
a & b: 101
a | b: 111
a ^ b: 010
~a: 010
a>>2: 001
a<<2: 10100
a>>>1: 010

Example of bitwise operators in Java:

 class BitwiseOperators{
    public static void main(String[] args){
        int a = 50, b = 10; // a is equal to 00110010 in binary, b is equal to 00001010 in binary

        System.out.println("a & b = " + (a & b));

        System.out.println("a | b = " + (a | b));

        System.out.println("a ^ b = " + (a ^ b));

        System.out.println("~a = " + (~a));

        System.out.println("a>>2 = " + (a>>2));

        System.out.println("a<<3 = " + (a<<3));

        System.out.println("a>>>4 = " + (a>>>4));

    }
} 

Output:

a & b = 2
a | b = 58
a ^ b = 56
~a = -51
a>>2 = 12
a<<3 = 400 a>>>4 = 3

The conversion to binary when working with bitwise operators is implicit, which means it automatically and implicitly converts numbers to binary to perform the bit-by-bit operation and then the result is still in the original base.

I suspect you should read this article for more detail about bitwise operators and this article to learn how to convert base 10 to base 2 if you haven’t learned about it yet.

Ternary Operators

The conditional operator or ternary operator ?: is shorthand for if-then-else statement (we will learn more about the if-else statements in upcoming articles). The syntax of the conditional operator is:

variable = Expression ? expression1 if true : expression2 if false

If the expression is true, then the expression1 will be assigned to the variable. If the expression is false, then the expression2 will be assigned to the variable. For example:

 class TernaryOperators{
    public static void main(String[] args){
        int a = 12, b = 7;
        String c = a > b ? "a is greater than b" : "a is not greater than b";
        System.out.println(c);
    }
} 

Here we have 2 numbers having the type of integer a and b, and string c which holds a sequence of characters. Because a is greater than b, then the first expression after ? will be assigned to the variable c, and if we run this program, we will get this result:

a is greater than b
Previous Article
Next Article
Every support is much appreciated ❤️

Buy Me a Coffee