Unit: 4 Operators

By Haitomns G

Operators in Java

Java provides rich set of operators to manipulate variable. We can divide all the Java operators into the following groups.

  • Arithmetic Operator
  • Relational Operator
  • Bitwise Operators
  • Logical Operator
  • Assignment Operations

Arithmetic Operator

Arithmetic operators are used in mathematical expression in same way that they are used in algebra. The following tables list are arithmetic operators.

Operator        Name                                     Description                                              Example

+                     Addition                                 Adds together two values                          x + y   

–                      Subtraction                           Subtracts one value from another            x – y   

*                      Multiplication                         Multiplies two values                                 x * y   

/                      Division                                  Divides one value by another                    x / y   

%                    Modulus                                 Returns the division remainder                x % y  

++                   Increment                              Increases the value of a variable by 1      ++x     

—                    Decrement                             Decreases the value of a variable by 1     –x

Example:

public class arithmetic{

    public static void main(String[] args){

        //Arithmetic Operators

        int a = 10;

        int b = 20;

        int c = 25;

        System.out.println(“a + b = ” + (a + b));

        System.out.println(“a – b = ” + (a – b));

        System.out.println(“a * b = ” + (a * b));

        System.out.println(“b / a = ” + (b / a));

        System.out.println(“b % a = ” + (b % a));

        System.out.println(“a++ = ” + (a++));

        System.out.println(“a– = ” + (a–));

        //Check the difference between ++ and —

        System.out.println(“++a = ” + (++a));

        System.out.println(“–a = ” + (–a));

    }

}

Output:

a + b = 30

a – b = -10

a * b = 200

b / a = 2

b % a = 0

a++ = 10

a– = 11

++a = 11

–a = 10

Bitwise Operators

Java defines several bid wise operating which can be applied to the integer type long and short gas and bite. The bit wise operator was used to control an interact with hardware and also for manipulating data at the bit level. The bitwise operator are stone in the table.

Operators                                          Symbol                                  Uses

Bitwise AND                                      &                                              op1 & op2

Bitwise exclusive OR                       ^                                              op1 ^ op2

Bitwise inclusive OR                        |                                               op1 | op2

Bitwise Compliment                         ~                                              ~ op

Bitwise right shift                             >>                                             op1 >> op2

Bitwise left shift                               <<                                             op1 << op2

Unsigned Right Shift Operator       >>> op >>>                               number of places to shift

Note: It cannot be applied in float or double. They can be applied in integer only.

Truth table for logical bitwise operators.

image 3
Truth table for logical bitwise operator

Bitwise AND Operator

The Bitwise and operator is represented by the symbol & (ampersand). The result of the AND operator is 1 if both operand bit are 1 otherwise, the result will be 0.

image
AND Operator Truth Table

Example:

Binary Value of 4 is             0100

Binary Value of 5 is              0101

 Gives                                   0100

Bitwise OR Operator

It is represented by the symbol | (vertical bar). It is also known as In-exclusive OR the result of the bitwise OR operation is 1 if the either or both corresponding bits has a value one, otherwise it is 0.

image 3
OR Operator Truth Table

Example:

Binary Value of 4 is             0100

Binary Value of 9 is               1001

  Gives                                1101

Bitwise Exclusive OR Operator

This operator is represented by the symbol ^ (caret), and also known as exclusive OR operator. The result of bitwise XOR operator is 1 if one of the corresponding bid is 1, otherwise the result is 0.

image 1
XOR Operator Truth Table

Example:

Binary Value of 4 is             0100

Binary Value of 9 is               1001

 Gives 1101

Bitwise Compliment Operators

The compliment operator is represented by ~ (tilde) and it is also known as 1’s complement operator. It inverts all the bit. Thus, all the zero becomes ones, and all the ones become zero.

image 2
Compliment Operator Truth Table

Example:

Binary Value of 4 is                         0100

Binary Value of ~4 is                      1011

Bitwise Shift Operators

 The shift operating RUP. The bit pattern to the right side or left side by the number. A bit given by their right operand.

1. Right Shift

The right shift operator is expression >> n.

When N is the number of bit positions to be shifted. However, the rightmost N bit are lost. Further, the left most N bit, which are vacant, will be filled with zero. For example: x>>4 Shift all bits by 4 placed do the right.

Example:

Consider and unsigned integer x with bit pattern,

                        0100 0100 0101 1100

When x>>3     000  0100 1000 1011

Last digit has Vacant Positions

When x>>5     0000  0010 0010 0010

Last digit has Vacant Positions

2. Left Shift

The right shift operator is expression << n.

Where N is the number of bit positions to be shifted. The leftmost N bit are lost, and the rightmost N bit are vacant and filled with zeros.

Example:

Consider and unsigned integer x with bit pattern,

                        0110 0111 1001 0011

When y<<1      1100  1111 0010 0110

Last digit has Vacant Positions

When y<<5     1111   0010 0110 0010

Last digit has Vacant Positions

3. Unsigned Right Shift Operator (>>>)

It shifts a zero at the leftmost position and fills 0. It is denoted by the symbol >>>. Note that the leftmost position after >> depends on the sign bit. It does not preserve the sign bit.

Example: If a=11110000 and b=2, find a>>>b?

a >>> b = 11110000 >>> 2 = 00111100

The left operand value is moved right by the number of bits specified by the right operand and the shifted bits are filled up with zeros. Excess bits shifted off to the right are discarded.

Therefore, before shifting the bits the decimal value of a is 240, and after shifting the bits the decimal value of a is 60.

Example of Bitwise Operators:

public class bitwise {

    public static void main(String[] args){

        //Bitwise Operators

        int a = 10;

        int b = 20;

        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 >> 2 = ” + (a >> 2));

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

    }

}

Output

a & b = 0

a | b = 30

a ^ b = 30

~a = -11

a << 2 = 40

a >> 2 = 2

a >>> 2 = 2

Bitwise Operator Compound Assignment

The bit wise assignment operator used to assign the value directly to the variables constant or expression to the variable. The table shows the list of Bitwise Operator Compound Assignment:

Operator           Description                                                                   Example           Equivalent

<<=                   It assigns the result of the signed left bit shift.          res <<= num       res = res << num

>>=                   It assigns the result of the signed right bit shift.         y >>= 1               y = y >> 1

&=                    It assigns the result of the logical AND.                        x &= 2               x = x & 2

^=                     It assigns the result of the logical XOR.                         a ^= b                a = a ^ b

|=                      It assigns the result of the logical OR.                            flag |= true        flag = flag | true

>>>=              It assigns the result of the unsigned right bit shift.         p >>>= 4           p = p >>> 4

Example:

public class bitwiseAssign {

    public static void main(String[] args) {

        // bitwise compound assignment

        int a = 10;

        int c = 5;

        c <<= 2;

        System.out.println(“c <<= 2 = ” + c);

        c >>= 2;

        System.out.println(“c >>= 2 = ” + c);

        c >>>= 2;

        System.out.println(“c >>>= 2 = ” + c);

        c &= a;

        System.out.println(“c &= a  = ” + c);

        c ^= a;

        System.out.println(“c ^= a   = ” + c);

        c |= a;

        System.out.println(“c |= a   = ” + c);

    }

}

Output:

c <<= 2 = 20

c >>= 2 = 5

c >>>= 2 = 1

c &= a  = 0

c ^= a   = 10

c |= a   = 10

Relational Operators

There are following Relational operators supported by Java Language.

image 4

Example:

public class relational {

    public static void main(String args[]){

        //relational operators

        int a = 10;

        int b = 20;

        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));

        System.out.println(“a <= b = ” + (a <= b));

    }

}

Output;

a == b = false

a != b = true

a > b = false

a < b = true

a >= b = false

a <= b = true

Logical Operators

Logical operators are used to combine two or more logical expressions. They are Logical AND, Logical OR and Logical NOT.

The following people released the logical operators.

image 4 1

Example:

public class logical {

    public static void main(String[] args) {

        //logical operators

        boolean a = true;

        boolean b = false;

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

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

        System.out.println(“!(a && b) = ” + (!(a && b)));       

    }

}

Output:

a && b = false

a || b = true

!(a && b) = true

Ternary Operator(?):

Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java programming. It is the only conditional operator which takes three operands.

Its syntax is:

condition ? expression1 : expression2;

Here, condition is evaluated and if condition is true, expression1 is executed. And, if condition is false, expression2 is executed. The ternary operator takes 3 operands (condition, expression1, and expression2). Hence, the name ternary operator.

Ternary Operator Example

public class OperatorExample{ 

public static void main(String args[]){ 

int a=2; 

int b=5; 

int min=(a<b)?a:b; 

System.out.println(min); 

}

Output:

2

Operator Precedence:

The operator precedence represents how two expressions are bind together. In an expression, it determines the grouping of operators with operands and decides how an expression will evaluate.

While solving an expression two things must be kept in mind the first is a precedence and the second is associativity.

Precedence

Precedence is the priority for grouping different types of operators with their operands. It is meaningful only if an expression has more than one operator with higher or lower precedence. The operators having higher precedence are evaluated first. If we want to evaluate lower precedence operators first, we must group operands by using parentheses and then evaluate.

Associativity

We must follow associativity if an expression has more than two operators of the same precedence. In such a case, an expression can be solved either left-to-right or right-to-left, accordingly.

Java Operator Precedence Table

The following table describes the precedence and associativity of operators used in Java.

PrecedenceOperatorTypeAssociativity
15()
[]
·
Parentheses
Array subscript
Member selection
Left to Right
14++
Unary post-increment
Unary post-decrement
Right to left
13++

+

!
~
(type)
Unary pre-increment
Unary pre-decrement
Unary plus
Unary minus
Unary logical negation
Unary bitwise complement
Unary type cast
Right to left
12*
/
%
Multiplication
Division
Modulus
Left to right
11+
Addition
Subtraction
Left to right
10<<
>>
>>>
Bitwise left shift
Bitwise right shift with sign extension
Bitwise right shift with zero extension
Left to right
9<
<=
>
>=
instanceof
Relational less than
Relational less than or equal
Relational greater than
Relational greater than or equal
Type comparison (objects only)
Left to right
8==
!=
Relational is equal to
Relational is not equal to
Left to right
7&Bitwise ANDLeft to right
6^Bitwise exclusive ORLeft to right
5|Bitwise inclusive ORLeft to right
4&&Logical ANDLeft to right
3||Logical ORLeft to right
2? :Ternary conditionalRight to left
1=
+=
-=
*=
/=
%=
Assignment
Addition assignment
Subtraction assignment
Multiplication assignment
Division assignment
Modulus assignment
Right to left

Java Operator Precedence Example

Let’s understand the operator precedence through an example. Consider the following expression and guess the answer.

1 + 5 * 3 

You might be thinking that the answer would be 18 but not so. Because the multiplication (*) operator has higher precedence than the addition (+) operator. Hence, the expression first evaluates 5*3 and then evaluates the remaining expression i.e. 1+15. Therefore, the answer will be 16.

Let’s see another example. Consider the following expression.

x + y * z / k 

In the above expression, * and / operations are performed before + because of precedence. y is multiplied by z before it is divided by k because of associativity.

Using Parentheses

Parentheses raise the precedence of the operations that are inside them. This is often necessary to obtain the result you desire. For example, consider the following expression:

a>> b+3 

This expression first adds 3 to b and then shifts a right by that result. That is, this expression can be rewritten using redundant parentheses like this:

a>> (b+3) 

However, if you want to first shift a right by b positions and then add 3 to that result, you will need to parenthesize the expression like this:

(a>> b)+3

In addition to altering the normal precedence of an operator, parentheses can sometimes be used to help clarify the meaning of an expression. For anyone reading your code, a complicated 17 expression can be difficult to understand. Adding redundant but clarifying parentheses to complex expressions can help prevent confusion later. For example, which of the following expressions is easier to read? 

a | 4 + c >> b & 7

(a |(((4 + c) >> b) & 7))

Note:  parentheses (redundant or not) do not degrade the performance of your program.

Also, Read

  1. Unit-1 Introduction to Mobile Application
  2. Unit-1 Java’s Lineage
  3. Unit-3 Data types, Variables and Array
  4. Computer Networking Notes

Haitomns G. is a desktop, android, and web developer based in Nepal. He has worked on building several websites, apps, and softwares for clients and independent projects. He is experienced in C, C++, C#, Java, Python, SQL, HTML, CSS, PHP, and JavaScript.

1 thought on “ Unit: 4 Operators”

  1. Please let me know if you’re looking for a article author for your blog. You have some really great posts and I believe I would be a good asset. If you ever want to take some of the load off, I’d love to write some articles for your blog in exchange for a link back to mine. Please blast me an email if interested. Cheers!

    Reply

Leave a Comment

Slide to prove you're not a bot/spammer *