Operators in Java

Operators in java are special symbols to perform specific operations. An operator in java may act on one or multiple operands, and then provides the desired result. A statement containing operands and operators is called expression.

For Example: In , 6 x (length + width)
+ and x are operators
6 is a constant operand
length and width are variables operand
"6 x(length + width)" is an expression, performing one logical task

Java programming language is rich in built in operators. we can broadly divide operators in following categories :

  • Arithmetic Operator
  • Logical Operator
  • Relational Operator
  • Assignment Operator
  • Unary Operator
  • Bitwise Operator
  • Ternary Operator
  • instanceof Operator

Arithmetic Operator

Arithmetic operators in java are used to perform mathematical operations in the same as in algebra. They are also called binary operators as they act on two operands at a time. Java supports five fundamental arithmetic operators, addition(+), subtraction(-), division(/), multiplication(*) and modulus(%). All binary arithmetic operators calculates result of specific arithmetic operation and returns it.

Operator Description Syntax Example
+ Adds two numbers a + b 15 + 5 = 20
- Subtracts two numbers a - b 15 - 5 = 10
* Multiplies two numbers a * b 15 * 5 = 75
/ Divides numerator by denominator a / b 15 / 5 = 3
10.0 / 4 = 2.5
% Modulo Operator. Returns remainder after an integer division a % b 15 % 5 = 0
16 % 5 = 1

Arithmetic Operators Example Program

public class ArithmeticOperators {
    public static void main(String[] args) {
        int i = 10;
        int j = 5;

        // Addition Operator
        System.out.println("i+j = " + (i + j));

        // Subtraction Operator
        System.out.println("i-j = " + (i - j));

        // Multiplication Operator
        System.out.println("i*j = " + (i * j));

        // Division Operator
        System.out.println("i/j = " + (i / j));

        // Modulo Operator
        System.out.println("i%j = " + (i % j));
    }
}
Output
i+j = 15
i-j = 5
i*j = 50
i/j = 2
i%j = 0

In the above java program, we have used +, -, *, /,and % operators to add, subtract, multiply, divide and modulo arithmetic operations.


Logical Operator

Logical operators in java used to combine two or more boolean expressions. Using logical operators we can create compound logical expressions.

Java programming language supports three logical operators &&(Logical AND), ||(Logical OR) and !(Logical NOT). All three logical operators returns boolean results, either true or false.

For Example :
"If age is less than 18 and weight is more than 45"
We can write above statement as follows :
if((age < 18) && (weight > 45))
Here we combined two boolean statements using logical and operator(&&).
  • || : Returns false, only if both operands are false, otherwise true.
  • && : Returns true, only if both operands are true otherwise false.
  • ! : Returns true if operand is false and Returns false if operand is true.
A B A && B A || B !A
TRUE FALSE FALSE TRUE FALSE
TRUE TRUE TRUE TRUE FALSE
FALSE TRUE FALSE TRUE TRUE
FALSE FALSE FALSE FALSE TRUE

Logical Operators Example Program

public class LogicalOperators {
    public static void main(String[] args) {
        int i = 10;
        int j = 5;
        // && OPERATOR
        // true && true = true
        System.out.println((i > j) && (j < i));
        // true && false = false
        System.out.println((i > j) && (j > i));
        // false && false = false
        System.out.println((i < j) && (j > i));

        // || OPERATOR
        // true || true = true
        System.out.println((i > j) || (j < i));
        // true && false = true
        System.out.println((i > j) || (j > i));
        // false && false = false
        System.out.println((i < j) || (j > i));

        // ! OPERATOR
        // !true = false
        System.out.println(!(i > j));
        // !false = true
        System.out.println(!(i < j));
    }
}
Output
true
false
false
true
true
false
false
true

Relational Operator

Relational operators in java are used to compare two values. All relational operators are binary operators as they act on two operands. Relational operators derives the relationship between two operators. Whether one operand is less than, greater than, equal to, or not equal to another operand.

All relational operators always returns boolean values either true or false.

For Example :

X < Y : It checks whether X is less than Y or not. If X is smaller than Y then it returns true else false.

X == Y : It checks if X and Y are equal or not. If X and Y are equal then it returns true else false.

Relational Operator Example Description
> A > B Checks if A is greater than B
< A < B Checks if A is less than B
>= A >= B Checks if A is greater than or equal to B
<= A <= B Checks if A is less than or equal to B
== A == B Checks if A is equal to B
!= A != B Checks if A is not equal to B

Relational Operators Example Program

public class RelationalOperators {
    public static void main(String[] args) {
        int i = 10;
        int j = 5;

        System.out.println("i = " + i + "; j = " + j);
        System.out.println("i > j : " + (i > j));
        System.out.println("i < j : " + (i < j));
        System.out.println("i >= j : " + (i >= j));
        System.out.println("i <= j : " + (i <= j));
        System.out.println("i == j : " + (i == j));
        System.out.println("i != j : " + (i != j));
    }
}
Output
i = 10; j = 5
i > j : true
i < j : false
i >= j : true
i <= j : false
i == j : false
i != j : true

Assignment Operator

Assignment operators in java are used to assign a value to a variable. It assigns the value on its right to the operand on its left.

For Example:
count = 1100;

Java programming also supports compound assignment operators or shorthand assignment. We may sometimes require to use same variable at both sides of assignment operator. In such cases, we can use compact notation by eliminating repetition of the variables. It first perform arithmetic operation between left and right operand and then assign the result to left operand.

For Example:

X*=4; is equivalent to X = X*4;
It first multiply X with 4, and then assign result to X.

Below is the list of Shorthand Assignment Operators Supported in Java.

Operator Example Equivalent Expression Description
+= A += B; A = A+B; It Adds A and B, then assign result to A
-= A -= B; A = A-B; It subtract B from A, then assign result to A
/= A /= B; A = A/B; It divides A by B, then assign result to A
*= A *= B; A = A*B; It multiply A and B, then assign result to A
%= A %= B; A = A%B; It takes modulus of A by B, then assign result A
&= A &= B; A = A&B; It does bitwise AND between A and B, then assign result to A
|= A |= B; A = A|B; It does bitwise OR between A and B, then assign result to A
^= A ^= B; A = A^B; It does bitwise XOR between A and B, then assign result to A
>>= A >>= B; A = A>>B; It does bitwise right shift, then assign result to A
<<= A <<= B; A = A< It does bitwise left shift, then assign result to A

Assignment Operators Example Program

public class AssignmentOperators {
    public static void main(String[] args) {
        int i = 10, j;
        System.out.println("i = " + i);

        j = i;
        System.out.println("j = i; j = " + j);

        j += i;
        System.out.println("j += i; j = " + j);

        j -= i;
        System.out.println("j -= i; j = " + j);

        j *= i;
        System.out.println("j *= i; j = " + j);

        j /= i;
        System.out.println("j /= i; j = " + j);

        j %= i;
        System.out.println("j %= i; j = " + j);
    }
}
Output
i = 10
j = i; j = 10
j += i; j = 20
j -= i; j = 10
j *= i; j = 100
j /= i; j = 10
j %= i; j = 0

Unary Operator

Unary operators in java operates on only one operands. They are used to perform various operations like incrementing and decrementing a variable, negating an expression. Java support following unary operators.

  • Unary minus operator (-) : is used to negate a given expression. To converting a positive value into negative value and vice–versa.

  • Increment operator (++) : increases the value of a variable by 1.

  • Decrement Operator (--) : is used to decrement the value of a variable by 1.

The increment and decrement operators can be attached either before(prefix) or after(postfix) operand. The expression ++var; and var++; will both increment the value of var but ++var first increment the value and return incremented value whereas var++; first return the value then increment the value of var.

Unary Operators Example Program

public class UnaryOperators {
    public static void main(String[] args) {
        int i = 10, j;
        System.out.println("i = " + i);

        j = ++i; // Increment before assignment.
        System.out.println("j = ++i; i = " + i + " j = " + j);

        j = i++; // Increment after assignment.
        System.out.println("j = i++; i = " + i + " j = " + j);

        j = --i; // Decrement before assignment.
        System.out.println("j = --i; i = " + i + " j = " + j);

        j = i--; // Decrement after assignment.
        System.out.println("j = i--; i = " + i + " j = " + j);
    }
}
Output
i = 10
j = ++i; i = 11 j = 11
j = i++; i = 12 j = 11
j = --i; i = 11 j = 11
j = i--; i = 10 j = 11

Bitwise Operator

The Java programming language support bitwise operators to perform operations on bits like assembly language. bitwise operators can only operates with byte, short, int, long and char data types. Bitwise operators performs bit-by-bit operations on operands.

Bitwise Operator Syntax Description
| A | B Bitwise OR Operator
& A & B Bitwise AND Operator
~ ~A NOT Operator(One's Complement)
^ A ^ B Bitwise Exclusive OR Operator
>> A >> B Right Shift Operator
<< A << B Left Shift Operator
>>> A >>> B Bitwise Zero Fill Right Shift Operator

Ternary Operator

Ternary operator is similar to if-then-else type of statement. It is an alternative to if-else statement. This operator is also known as the conditional operator because it uses three operands. Here is the syntax of ternary operator.

Conditional_Expression ? Expression_One : Expression_Two;

Ternary Operator will execute Expression_One if Conditional_Expression is true, otherwise it execute Expression_Two. Either Expression_One or Expression_Two will execute, both cannot get executed.

For Example,
(X > 10) ? (X++) : (X--);

Ternary Operators Example Program

public class TernaryOperator {
    public static void main(String[] args) {
        int marks = 50;
        String result;

        // Ternary operator
        result = (marks > 40) ? "PASSED" : "FAILED";
        System.out.println("Result = " + result);
    }
}
Output
Result = PASSED

Instanceof Operator

instanceof is a boolean operator which is used to check if an object reference is an instance of a type. It always returns a boolean value. We use this class to check whether an object is an instance if a class or it's subclass.

InstanceOf Operator Example Program

public class InstanceofOperators {
    public static void main(String[] args) {
        String str = String.valueOf("Java");
        boolean isString;

        isString = (str instanceof String) ? true : false;
        System.out.println("IsString = " + isString);
    }
}
Output
IsString = true

Operator Precedence Java

Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated before operators with lower precedence. When an expression contains multiple operators, Java follows a specific order to evaluate them.

Here is a list of operators in Java, sorted by precedence (from highest to lowest):

Postfix operators: expr++ and expr--
Unary operators: ++expr, --expr, +expr, -expr, ~, and !
Multiplicative operators: *, /, and %
Additive operators: + and -
Shift operators: <<, >>, and >>>
Relational operators: <, <=, >, and >=
Equality operators: == and !=
Bitwise AND: &
Bitwise XOR: ^
Bitwise OR: |
Logical AND: &&
Logical OR: ||
Conditional operator: ? :
Assignment operators: =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, and >>>=
    
Parentheses () can be used to override the default precedence and explicitly specify the order of evaluation.
int result = (5 + 3) * 2;
// Result: 16 ( (5 + 3) * 2, parentheses override default precedence)

Associativity in Java

Associativity determines the order in which operators of the same precedence are evaluated. There are two types of associativity: left-to-right and right-to-left.

  • Left-to-right associativity : Operators are evaluated from left to right.
    Example: a + b + c is evaluated as (a + b) + c.

  • Right-to-left associativity : Operators are evaluated from right to left.
    Example: a = b = c is evaluated as a = (b = c).
Most operators in Java have left-to-right associativity. The assignment operators (=) have right-to-left associativity.