Java Operators Tutorial

In this Java tutorial we learn the standard arithmetic, assignment, comparison (relational) and logical (conditional) operators.

We also discuss the negation, concatenation, typeof and ternary operators as well as operator precedence in Java.

What are operators

Operators are one or more symbols in Java that is special to the compiler and allows us to perform various operations within our application.

As an example, let’s consider the + symbol. The + symbol is an operator to perform arithmetic on two or more numeric values.

But, when used on two or more strings, the + operator will combine (concatenate) them into a single string.

Example:
// addition
System.out.println(5 + 3);

// concatenation
System.out.println("Hello " + "World");

Operators in Java can be classified based on two criteria.

1. The number of operands.

If an operator takes a single operand, it’s called a unary operator. If it takes two operands, it’s called a binary operator. If it takes three operands, it’s called a ternary operator.

2. The type of operation performed.

Based on the operation, an operator can be called an arithmetic operator, an assignment operator, a bitwise operator, a comparison (relational) operator, or a logical (conditional) operator.

Arithmetic operators in Java

Java supports the following the arithmetic operators.

OperatorDescriptionExample
+Adds operands5 + 3 = 8
-Subtract the second operand from the first5 - 3 = 2
*Multiplies the first operand with the second5 * 3 = 15
/Divide the first operand with the second5 / 3 = 1
%Modulus. Returns the remainder of a division5 % 3 = 2
++Increment. Increase an interger value by one5++ = 6
--Decrement. Decrease an integer value by one5-- = 4

Assignment operators in Java

Java supports the following assignment operators.

OperatorDescription
=Assignment. Assign right operand to the left operand
+=Add and assign. Add the right operand to the left operand and assign the result to the left operand
-=Subtract and assign. Subtract the right operand from the left operand and assign the result to the left operand
*=Multiply and assign. Multiply the left operand with the right operand and assign the result to the left operand
/=Divide and assign. Divide the left operand with the right operand and assign the result to the left operand
%=Modulus and assign. Divide the left operand with the right operand and assign the remainder to the left operand
Example:
public class Program {
    public static void main(String[] args) {

        // =
        int num1 = 5, num2 = 3;
        System.out.println("num1: " + num1);

        // +=
        num1 += num2;
        System.out.println("num1 += num2: " + num1);

        // -=
        num1 -= num2;
        System.out.println("num1 -= num2: " + num1);

        // *=
        num1 *= num2;
        System.out.println("num1 *= num2: " + num1);

        // /=
        num1 /= num2;
        System.out.println("num1 /= num2: " + num1);

        // %=
        num1 %= num2;
        System.out.println("num1 %= num2: " + num1);
    }
}

Comparison (Relational) operators in Java

Java supports the following comparison operators.

OperatorDescription
==Evaluates if the values of two operands are equal
!=Evaluates if the values of two operands are not equal
>Evaluates if the value of the left operand is greater than the value of the right operand
<Evaluates if the value of the left operand is less than the value of the right operand
>=Evaluates if the value of the left operand is greater than or equal to the value of the right operand
<=Evaluates if the value of the left operand is less than or equal to the value of the right operand
Example:
public class Program {
    public static void main(String[] args) {

        boolean result = false;

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

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

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

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

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

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

Logical (Conditional) operators in Java

Java supports the following comparison operators.

OperatorNameDescription
&&Conditional AND operatorIf both operands are non-zero, the result is true
||Conditional OR operatorIf one of the two operands is non-zero, the result is true
!Conditional NOT operatorIf the condition is not true, the result becomes true
Example:
public class Program {
    public static void main(String[] args) {

        boolean op1 = true;
        boolean op2 = false;

        // &&
        System.out.println("op1 AND op2 = true: " + (op1 && op2));

        // ||
        System.out.println("op1 OR op2 = true: " + (op1 || op2));

        // !
        System.out.println("op1 = NOT true: " + !op1);

        // !
        System.out.println("op2 = NOT true: " + !op2);
    }
}

Other: The negation operator in Java

Typically, if we want to to turn a positive number into a negative number, we would have to multiply that number by -1.

Example:
public class Program {
    public static void main(String[] args) {

        // positive number
        int num = 5;
        System.out.println(num);

        // prefix number with
        // negation operator ( - )
        System.out.println(num * -1);
    }
}

The negation operator can turn a number negative simply be prefixing it with the - (minus) operator.

Example:
public class Program {
    public static void main(String[] args) {

        // positive number
        int num = 5;
        System.out.println(num);

        // prefix number with
        // negation operator ( - )
        System.out.println(-num);
    }
}

Other: The concatenation operator in Java

When working with arithmetic, the + operator will perform an addition. But, when working with strings, it will combine (concatenate) the strings together.

Example:
public class Program {
    public static void main(String[] args) {

        String msg1 = "Hello";
        String msg2 = " there";

        // concatenate the strings
        // with the + operator
        System.out.println(msg1 + msg2);
    }
}

Other: The typeof operator in Java

Java does not have a ‘typeof’ operator to get and return the data type of the operand we specify.

Instead, we use the getClass() method on a variable object with the getName() or getSimpleName() methods after it.

If you’re a beginner and this doesn’t make sense right now, don’t worry about this section. We cover classes and class methods in the OOP: Classes and Objects lesson .

Syntax:
// variable init
var_type var_name = value;

// assign to object
Object name = var_name;

// get the type
name.getClass().getName();
// or
name.getClass().getSimpleName();
Example:
public class Program {
    public static void main(String[] args) {

        // variable init
        String msg = "Hello there";

        // assign to object
        Object findType = msg;

        // get the type
        System.out.println( msg.getClass().getSimpleName() );
    }
}

The code above can be separated into a function if we find ourselves needing it often.

Example:
public class Program {

    public static void main(String[] args) {

        byte num1 = 5;
        String msg = "Hello there";

        printTypeOf(num1);
        printTypeOf(msg);
    }

    // function to get and print
    // variable or object type
    public static void printTypeOf(Object typeOf) {

        System.out.println("Type: " + typeOf.getClass().getSimpleName() + " - Value: " + typeOf);
    }
}

In the example above, the ‘printTypeOf’ function will get and print the type, as well as the value of the variable or object.

Output:
Type: Byte - Value: 5
Type: String - Value: Hello there

Other: The ternary operator in Java

The ternary operator is a shorthand method of writing a if/else statement that only contains a single execution statement.

If you’re a beginner and this doesn’t make sense right now, don’t worry about this section. We cover the ternary statement again in the Conditional Control lesson .

Let’s consider the following if else statement.

Example:
public class Program {
    public static void main(String[] args) {

        byte num = 8;

        if (num == 10) {

            System.out.println("num == 10");
        } else {

            System.out.println("num != 10");
        }
    }
}

In the example above, we evaluate if a number is 10 or not and print a message to the console. Let’s convert this into shorthand with the ternary operator.

Example:
public class Program {
    public static void main(String[] args) {

        byte num = 5;

        // result       condition     if true statement   if false statement
        String result = (num == 10) ? "num == 10"       : "num != 10";

        System.out.println(result);
    }
}

In the example above, we assign the result of the ternary operation to a variable called ‘result’. Then, we print it to the console.

Syntax:
 boolean-expression ? true-expression : false-expression

Operator precedence in Java

Certain operators in Java will have higher precedence than others.

As an example, let’s consider the precedence of the multiplication and addition operators.

Example:
 5 + 3 * 2

If we read the calculation from left to right, we would do the addition first. But, the multiplication operator has a higher precedence than the addition operator, so it will do that part of the calculation first.

Example:
// correct
3 * 2 = 6
5 + 6 = 11

// incorrect
5 + 3 = 8
8 * 2 = 16

We can change the operator precedence by wrapping operators in parentheses.

Example:
 (5 + 3) * 2

In the example above, we want the addition to be performed before the multiplication, so we wrap the addition in parentheses.

Example:
(5 + 3) = 8
8 * 2 = 16

Summary: Points to remember

  • Operators are symbols that have a special meaning to the compiler.
  • Java supports the typical arithmetic, assignment, comparison (relational) and logical (conditional) operators.
  • Java also supports the negation, concatenation, typeof and ternary operators.
  • Some operators have greater importance than others and we change operator precedence with parentheses.