Java Operators Tutorial

97 views

In this tutorial, we will go through all operators that exist in Java and explain when, how, and why you should use them.

1. Java Operators Overview

Operators in Java are symbols that are used in combination with variables, in order to perform specific actions. You have used operators many times in your math classes, since +, -, /, * etc. are operators.

Also, there are two categories of operators based on where they are applied:

  1. Prefix Operators
  2. Postfix Operators

Prefix operators are applied before a variable (e.g. --x) whereas postfix operators are applied after a variable (e.g x--).

What changes here is that the value returned by the expression is the new value when using prefix operators but when using postfix operators, the value returned is the old value.

Below is a simple demonstration:

        int x = 100;

        int j = --x;
        // Now j has the new value of x
        // so it will print 99
        System.out.println(j);
        int k = x--;
        // Now k has the old value of x
        // so it will print 99
        System.out.println(k);
        // x is 98
        System.out.println(x);

In the following sections, we’ll go through all types of operators one by one and analyze them with examples.

2. Java Unary Operators

2.1 ++variable and –variable

        //++variable operator
        int x = 100;
        // This increments x by one and returns the new value
        // 101
         int j = ++x;
        //Now both j and x have the same value
        System.out.println(j == x);

        //--variable operator
        int y = 100;
        // This decrements x by one and returns the new value
        // 99
        int k = --y;
        //Now both y and k have the same value
        System.out.println(y == k);

This will print:

true
true

2.2 !variable

The negation operator is only applied to boolean variables, and what it does, is that it negates the value of the boolean variable.

        //!variable operator
        boolean flag = false;
        boolean newFlag = !flag;
        // This will print true
        System.out.println(newFlag);

Output:

true

2.4 +variable With Strings

Operator + can be used to concatenate String variables together.

        // +variable between non-arithmetic variables
        String hello = "Hello";
        String space = " ";
        String world = "world!";
        String helloWorld = hello + space + world;
        // This concatenates the strings
        System.out.println(helloWorld);

This will print Hello world!.

3. Java Arithmentic Operators

Arithmetic operators are used for performing calculations between numbers. You already know most of them from your math classes. However, there are some differences between common math and Java. Before going through this section, I would suggest that you visit the primitives tutorial, in order to get the most of this section.

3.1 Addition and Subtraction

These are the + and – operators and they just perform additions and subtractions:

        int x = 5;
        x = x + 10;
        System.out.println(x);
        int j = 20;
        j = j - 5;
        System.out.println(j);

This will just print 15 and 15.

3.2 Multiplication and Division

Multiplication operators work like the multiplication you would do at a calculator. On the contrary, the division is a bit different.

3.2.1 Working With Integers

When working with integers, you can perform multiplication using the * operator, but only between integers, should you want to continue storing the result to an int variable

If you want to multiply an integer with a double, then the result must be double or cast the result to int like below:

        int x = 20;
        x = x * 5;
        System.out.println(x);
        // You can't do that without casting to int
        // x = x * 5.5;
        x = (int) (x * 5.5);
        System.out.println(x);
        // You can however create a new double to store the result
        double res = x * 3.95;
        System.out.println(res);

The output will be:

100
550
2172.5

With regard to division, by default when dividing 2 integers, the calculation will be an integer division. To get the quotient you must use / operator, and to get the remainder, the % operator.

        int z = 20;
        // Quotient
        int quotienInt = z / 3;
        System.out.println("Quotient is: "+quotienInt);
        //Remainder
        int remainderInt = z % 3;
        System.out.println("Remainder is: "+remainderInt);

The result of this will be:

Quotient is: 6
Remainder is: 2

3.2.1 Working With Floating-Point Numbers

When dealing with double numbers, multiplication works like the multiplication on your calculator, and the same applies to the division with / operator. When doing mod (%) division with double numbers, the result is the remainder of an exact division.

        double y = 30.2;
        y = y * 3.2;
        System.out.println(y);

        // Double division
        double a = 5.2;
        double quotientDouble = 5.2/3;
        double remainderDouble = 5.2 % 3.2;
        System.out.println(quotientDouble);
        System.out.println(remainderDouble);

The output will be:

96.64
1.7333333333333334
2.0

4. Java Comparison Operators

These operators are the commonly used comparison, equality, and inequality operators that you most certainly used in your math class.

4.1 a > b, b >= b, a < b and a <= b

        // greater than and less than
        System.out.println("5 > 10: "+ (5 > 10));
        System.out.println("5 < 10: "+ (5 < 10));
        System.out.println();

        // With chars
        // the ASCII code will be compared
        System.out.println("'A' numeric value is "+Character.getNumericValue('A'));
        System.out.println("'B' numeric value is "+Character.getNumericValue('B'));
        System.out.println("A > B: "+('A' > 'B'));
        System.out.println();

        //greater or equal
        System.out.println("5 >= 10: "+ (5 >= 10));
        System.out.println("5 <= 10: "+ (5 <= 10));
        System.out.println();

The output is:

5 > 10: false
5 < 10: true

'A' numeric value is 10
'B' numeric value is 11
A > B: false

5 >= 10: false
5 <= 10: true

4.2 == and !=

        // equality
        System.out.println("5 == 10: "+ (5 == 10));
        System.out.println("5 == 5: "+ (5 == 5));
        System.out.println();
        // inequality
        System.out.println("5 != 10: "+ (5 == 10));
        System.out.println("5 != 5: "+ (5 == 5));
        System.out.println();

This will print:

5 == 10: false
5 == 5: true

5 != 10: false
5 != 5: true

4.3 Comparison With Objects and instanceof Operator

4.3.1 >, >=, <, <= Operators

You should have in mind that you cannot compare Objects with the aforementioned operators since Java does not support operator overloading. However, your Object could implement the Comparable interface and define your own custom comparison methods.

4.3.2 == and != With Objects

These operators cannot be used with Objects and Strings since the result will not be the expected, as this will compare the references of the objects. In order to compare Objects and Strings, you should use the equals() method.

Note that if for any reason you override equals(), you should also override hashCode() method to have the expected results.

Below is a demonstration of why the == would not work with Strings and why we should use the equals() method.

        String hello = "Hello";
        // This string is now in the String pool
        
        String hello1 = "Hello";
        // The hello1 variable just
        // points to the same reference as of hello variable

        // This will print true since the reference is compared
        System.out.println("hello == hello1? "+(hello == hello1));
        // What if we force the creation of a new reference?
        String hello2 = new String("Hello");
        // This will be false even though the string is the same
        System.out.println("hello2 == hello? "+(hello2 == hello));
        // This will be true, as expected
        System.out.println("hello2.equals(hello)? "+hello2.equals(hello));

And the output will be:

hello == hello1? true
hello2 == hello? false
hello2.equals(hello)? true

4.3.3 instanceof Operator

This operator is used to determine whether an Object is a descendant of a specific class.

In order to understand this operator, we have created 2 classes:

  1. Person class which does not extend any class
  2. Employee class which extends Person class
        Person person = new Person();
        Employee employee = new Employee();

        System.out.println("person instanceof Person: "+(person instanceof Person));
        System.out.println("person instanceof Employee: "+(person instanceof Employee));

        System.out.println("employee instanceof Person: "+(employee instanceof Person));
        System.out.println("employee instanceof Employee: "+(employee instanceof Employee));

The output will be:

person instanceof Person: true
person instanceof Employee: false
employee instanceof Person: true
employee instanceof Employee: true

Some notes here:

  • instanceof will always return true if the second operand is Object
  • instanceof does not work backwards; a parent class is not an instance of the child class

5. Java Logical Operators

The logical operators are AND (&& in Java) and OR (|| in Java). They are used to combine boolean expressions and produce a boolean result. Note that you can use nested ANDs and ORs for more complicated logic.

5.1 && Operator

This operator combines 2 boolean expressions and produces true only if both of them are true. If any of them is false, the other comparison will not continue and the whole expression will be evaluated to false:

        if (true && 5>0)
            System.out.println(true);
        else
            System.out.println(false);

        if (false && 5>0)
            System.out.println(true);
        else
            System.out.println(false);

Output:

true
false

5.2 || Operator

This operator combines 2 boolean expressions and produces true if at least one of them is true. If the first one is true, the other expression will not be evaluated and the whole expression will return true.

        if (true || 5>0)
            System.out.println("true");
        else
            System.out.println(false);

        if (false || 5>0)
            System.out.println(true);
        else
            System.out.println(false);

And the output will be:

true
true

6. Java Ternary Operator

This operator is used to concisely return a value based on the outcome of a boolean expression.

Its syntax is the following:

boolean_expression ? return_this_if_true : return_this_if_false

It can be used in assignments or when returning a value from a method.

Let’s jump to an example:

    public static void main(String[] args) {

        // x will be 10
        int x = true ? 10 : 20;
        // y will be 20
        int y = false ? 10 : 20;

        System.out.println(getRandomInt(0));
        System.out.println(getRandomInt(10));
    }

    // returns 0, if the input is 0,
    // returns a random number, if input is other than 0
    private static double getRandomInt(int x){
        return x == 0 ? 0 : Math.random();
    }

An output could be:

0.0
0.10280818322491803

7. Java Bitwise Operators

Bitwise operators perform calculations based on the binary value of a variable:

7.1 Bitwise AND (& in Java)

The table below describes what the result will be for each & operation performed between 2 operands. The parenthesis describes the result in binary.

1st operand2nd operandResult
true(1)true(1)true(1)
true(1)false(0)false(0)
false(0)true(1)false(0)
false(0)false(0)false(0)
Figure 1. AND truth table

7.1.1 Booleans

When working with booleans, the difference with Logical AND (&&) is that it will check both operands, no matter the result of the first.

        int x = 100;
        System.out.println("false & true: "+(false & --x == 99));
        System.out.println("Now x is decreased by 1, x is:"+x);
        //whereas with logical AND
        System.out.println("false && true: "+(false && --x == 99));
        System.out.println("Now x doesn't change, x is:"+x);

The output is:

false & true: false
Now x is decreased by 1, x is:99
false && true: false
Now x doesn't change, x is:99

7.1.2 Integers

When dealing with integers, the result will be produced based on the result of the table at the beginning of the section, when applied to each bit of the binary value.

        //1100100 in binary
        int z = 100;
        //1100101 in binary
        int y = 101;
        
        /* 1100100 is the result of
         * 1100100 & 1100101
         * which is 100 in binary
         * So that will print 100
        */ 
        System.out.println(z & y);

7.2 Bitwise OR (| in Java)

The table below describes what the result will be for each | operation performed between 2 operands. The parenthesis describes the result in binary.

1st operand2nd operandResult
true(1)true(1)true(1)
true(1)false(0)true(1)
false(0)true(1)true(1)
false(0)false(0)false(0)
Figure 2. OR truth table

7.2.1 Booleans

When working with booleans, the difference with Logical OR (||) is that it will check both operands, no matter the result of the first.

        int a = 100;
        System.out.println("true | false: "+(true | --a == 99));
        System.out.println("Now a is decreased by 1, a is:"+a);
        //whereas with logical OR
        System.out.println("true | false: "+(true || --a == 99));
        System.out.println("Now a doesn't change, a is:"+a);

The output is:

false & true: false
Now x is decreased by 1, x is:99
false && true: false
Now x doesn't change, x is:99

7.2.2 Integers

When dealing with integers, the result will be produced based on the result of the table at the beginning of the section, when applied to each bit of the binary value:

         //integers
        //1100100 in binary
        int z = 100;
        //1100101 in binary
        int y = 101;

        /* 1100101 is the result of
         * 1100100 | 1100101
         * which is 101 in binary
         * So that will print 101
         */
        System.out.println(z | y);

7.3 Bitwise XOR (^ in Java)

The table below describes what the result will be for each ^ operation performed between 2 operands. The parenthesis describes the result in binary.

1st operand2nd operandResult
true(1)true(1)false(1)
true(1)false(0)true(1)
false(0)true(1)true(1)
false(0)false(0)false(0)
Figure 3. XOR truth table

7.3.1 Booleans

This operator is the eXclusive OR, and the result, when applied to 2 booleans will be true only if one of the operands is true. If we run the following:

        System.out.println("true ^ false: "+(true ^ false));
        System.out.println("false ^ true: "+(false ^ true));
        System.out.println("false ^ false: "+(false ^ false));
        System.out.println("true ^ true: "+(true ^ true));

It will print:

true ^ false: true
false ^ true: true
false ^ true: false
true ^ true: false

7.3.2 Integers

When dealing with integers, the result will be produced based on the result of the table at the beginning of the section, when applied to each bit of the binary value.

        //1100100 in binary
        int z = 100;
        //1100101 in binary
        int y = 101;

        /* 0000001 is the result of
         * 1100100 ^ 1100101
         * which is 1 in binary
         * So that will print 1
         */
        System.out.println(z ^ y);

7.4 Bitwise Complement (~ in Java)

The table below describes what the result will be for each ~ operation performed between 2 operands. The parenthesis describes the result in binary. On the contrary with the aforementioned operators, it cannot be applied to boolean variables

OperandResult
true(1)false(0)
false(0)true(1)
Figure 4. Complement truth table

When dealing with integers, the result will be produced based on the result of the table above, when applied to each bit of the binary value:

         //1100100 in binary
         int z = 100;
         //This will print -101 since
         //~1100100 in 2's complement is
        //1111111110011011
        System.out.println(~z);

8. Java Shift Operators (<<, >>, >>>)

Shift operators shift the bits of the 1st operand as many times as specified in the 2nd operand.

8.1 Left shift (<<)

The formula is the following:

x << y == x * 2^y

Below you can find some examples:

        // Is like 100 * 2^2 = 100*4 = 400
         System.out.println(100<<2);

        // Is like 33 * 2^3 = 33*8 = 264
        System.out.println(33<<3);

The output will be as expected:

400
264

8.2 Arithmetic Right Shift (>>) and Logical Right Shift (>>>)

The formula is the following:

x >> y == x / 2^y

Below you can find some examples:

        // Is like 100 / 2^2 = 100*4 = 400
        System.out.println(100>>2);

        // Is like 33 / 2^3 = 33/8 = 4
        System.out.println(33>>3);

The output will be as expected:

25
4

The logical shift is exactly like the arithmetic shift but does not preserve the sign bit.

        // This will print 25
        System.out.println(100>>2);
        // This will also print 25
        System.out.println(100>>>2);
        // This will print -25
        System.out.println(-100>>2);
        // This will print 1073741799
        System.out.println(-100>>>2);

9. Java Assignment Operators (=)

The most common assignment operator is = and you most likely use it all the time to assign values to variables.

However, there are combinations between all the aforementioned operators with the = operator.

The formula is the following:

a += b is exactly like a = a + b
a -= b is exactly like a = a - b
a *= b is exactly like a = a * b
a /= b is exactly like a = a / b
a %= b is exactly like a = a % b
a &= b is exactly like a = a & b
a ^= b is exactly like a = a ^ b
a |= b is exactly like a = a | b
a <<= b is exactly like a = a << b
a >>= b is exactly like a = a >> b
a >>>= b is exactly like a = a >>> b

Below you can find some examples of how they can be used.

Calculate sum example:

    private static int calculateSum(List<Integer> numbers){
        int sum = 0;
        for(int number : numbers){
            sum += number;
        }
        return sum;
    }

Calculate power example:

    private static double calculatePower(double base, int exponent){
        double result = 1;
        int abs = Math.abs(exponent);
            for(int i = 0; i < abs; i++){
                result *= base;
            }
        return exponent >= 0 ? result : 1/result;
    }

10. Java Dot operator (.)

This operator is used to access a member, method, or inner class of a class or an Object. To learn more about how classes work, you can check our article on Java classes.

Let’s jump to some examples to demonstrate basic usage:

        // dot operator is used to access a static method of Math class
        double x = Math.random();
        // dot operator is used to access a method of an object
        String a = "hello".toUpperCase();
        
        int [] array = new int[5];
        // dot operator is used to access a member
        int len = array.length;

11. Java Lambda function operator (->) and method reference operator (::)

The arrow operator (->) is used to define a lambda function.

The formula of a lambda function is the following:

(parameter_1, parameter_2, ..., parameter_n) -> {}

Another operator the is used with lambdas is the method reference operator (::). This operator is used to reference a method instead of providing a lambda function.

Below you can find an example of how would these 2 work in action:

        List<String> names = Arrays.asList("Giannis", "Dimitris", "Akis");
        names = names.stream()
                .filter(name -> name.startsWith("A")) // Here we use a Lambda function
                .map(String::toLowerCase)// Here we use method reference
                .collect(Collectors.toList());
        // This will print only the names that start with A after converting to lowercase
        names.forEach(System.out::println);

12. Conclusion

By now, you should know everything about operators in Java, and how to use them the best way possible. You can find the source code of the example on our GitHub page. Happy learning!

13. Sources

[1]: Summary of Operators – Oracle

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

Related Posts