Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

MODULE OF INSTRUCTION

4. Operators and Operator Precedence

In this module, we are going to discuss the different operators that can
be use in Java.

At the end of this lesson, you should be able to:

- Identify the different operators in Java.

- Enumerate the operator precedence.

- Develop a simple program using the concepts mentioned


above.

4.1 Operator

An operator is a symbol that is used to perform a specific


mathematical or logical operation. In Java, we use different types of
operators and these are the following:

 Arithmetic Operators
 Relation Operators
 Logical Operators
 Conditional Operator
 Bitwise and Bit Shift Operators
 Assignment Operators

4.1.1 The Arithmetic Operators

Arithmetic operators are used to perform a basic computation


in a program and it operates the same way that they are used in
algebra. The table below shows the list of arithmetic operators:

*Let us assume that the value of x = 15 and y = 5


Operator Example Result Description
+ (Addition) x+y 20 Adds the value of x and y

Computer Programming 2 1
Week 3-4 Operator and Operator Precedence

- (Subtraction) x-y 10 Subtracts the value of y from x


*
x*y 75 Multiplies the value of x by y
(Multiplication)
/ (Division) x/y 3 Divides the value of x by y.
Divides the value of x by y and get the
% (Modulus) x%y 0
remainder.
x++ (post) 15
++ (Increment) Increment the value of x by 1.
++x (pre) 16
x—(post) 15
-- (Decrement) Decrement the value of operand by 1.
--x (pre) 14

Below is the sample program that implements arithmetic operators:

public class ArithmeticOperatorsDemo {


public static void main(String[] args) {
int x = 13;
int y = 9;
double result = 0;

System.out.println("Variable values:");
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("result = " + result);

System.out.println(); //add a new line


System.out.println("Arithmetic Operation:");

result = x + y; //performs addition


System.out.println("Addition: x + y = " + result);

result = x - y; //performs subtraction


System.out.println("Subtraction: x - y = " + result);

result = x * y; //performs multiplication


System.out.println("Multiplication: x * y = " + result);

result = x / y; //performs division


System.out.println("Division: x / y = " + result);

result = x % y; //gets the remainder


System.out.println("Modulus: x % y = " + result);

2
MODULE OF INSTRUCTION

result = x++; //increment by 1


System.out.println("Increment: x++ = " + result);

result = x--; //decrement by 1


System.out.println("Decrement: x-- = " + result);
}
}

The output of the program above is:

The Relational Operators

Relational operator is an operator that compares two values.


When you use a relational operator in an operation the result is a
Boolean value (either true or false). The table below shows the list of
relational operators:

*Let us assume that the value of x and y is 5


Operator Example Result Description

Checks if the two values are equal,


== (equal to) x==y true if yes then the result is true,
otherwise false.

Checks if the two values are not


!= (not equal to) x!=y false equal, if yes then the result is true,
otherwise false.

Computer Programming 2 3
Week 3-4 Operator and Operator Precedence

Checks if the value of x is greater


> (greater than) x>y false than the value of y, if yes the result
is true, otherwise false.

Checks if the value of x is less than


< (less than) x<y false the value of y, if yes the result is
true, otherwise false.

Checks if the value of x is greater


>= (greater than than or equal to the value of y, if
x>=y true
or equal to) yes the result is true, otherwise
false.

Checks if the value of x is less than


<= (less than or
x<=y true or equal to the value of y, if yes the
equal to)
result is true, otherwise false.

Below is the sample program that implements relational operators:

public class RelationalOperatorsDemo {


public static void main(String[] args) {
int x = 5;
int y = 10;
int z = 5;
boolean result;

System.out.println(); //add a new line


System.out.println("Relational Operation:");

System.out.println(); //add a new line


System.out.println("Equal to:");
result = x == y; //checks if the two values are equal
System.out.println(x + " == " + y + " = " + result);
result = x == z; //checks if the two values are equal
System.out.println(x + " == " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Not equal to:");
result = x != y; //checks if the two values are not equal
System.out.println(x + " != " + y + " = " + result);
result = x == z; //checks if the two values are equal

4
MODULE OF INSTRUCTION

System.out.println(x + " != " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Greater than:");
result = y > x; //checks if the two values are not equal
System.out.println(y + " > " + x + " = " + result);
result = x > z; //checks if the two values are equal
System.out.println(x + " > " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Less than:");
result = x < y; //checks if the two values are not equal
System.out.println(x + " < " + y + " = " + result);
result = x < z; //checks if the two values are equal
System.out.println(x + " < " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Greater than or equal to:");
result = y >= x; //checks if the two values are not equal
System.out.println(y + " >= " + x + " = " + result);
result = x >= z; //checks if the two values are equal
System.out.println(x + " >= " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Less than or equal to:");
result = x <= y; //checks if the two values are not equal
System.out.println(x + " <= " + y + " = " + result);
result = x <= z; //checks if the two values are equal
System.out.println(x + " <= " + z + " = " + result);
}
}

The output of the program above is:

Computer Programming 2 5
Week 3-4 Operator and Operator Precedence

The Logical Operators

Logical operator is an operator that can only be use in an


operation with Boolean values. Like relational operator, it also returns
is a Boolean value. The table below shows the list of relational
operators:

*Let us assume that the value of x=true and y = false


Operator Example Result Description

6
MODULE OF INSTRUCTION

This operator is called Logical


AND operator. If the boolean
&& (logical
x && y False values of both operands are true,
and)
the result will be true, otherwise
false.

This operator is called Logical


OR operator. If there is one
|| (logical or) x || y True operand that has boolean values
of true, the result will be true,
otherwise false.

This operator is called Logical


NOT operator. It returns the
opposite value of its operand. If
! (logical not) !x False an operand to right is true, the
result will be false. And if the
operand to the right is false, the
result will be true.

Below is the sample program that implements logical operators:

public class LogicalOperatorsDemo {


public static void main(String[] args) {
boolean x = true;
boolean y = false;
boolean result;

System.out.println("Logical Expression:");

System.out.println(); //add a new line


System.out.println("Logical AND:");
result = x && x; //result here is true
System.out.println(x + " && " + x + " = " + result);
result = x && y; //result here is false
System.out.println(x + " && " + y + " = " + result);
result = y && x; //result here is false
System.out.println(y + " && " + x + " = " + result);
result = y && y; //result here is false

Computer Programming 2 7
Week 3-4 Operator and Operator Precedence

System.out.println(y + " && " + y + " = " + result);

System.out.println(); //add a new line


System.out.println("Logical OR:");
result = x || x; //result here is true
System.out.println(x + " || " + x + " = " + result);
result = x || y; //result here is true
System.out.println(x + " || " + y + " = " + result);
result = y || x; //result here is true
System.out.println(y + " || " + x + " = " + result);
result = y || y; //result here is false
System.out.println(y + " || " + y + " = " + result);

System.out.println(); //add a new line


System.out.println("Logical NOT:");
result = !x; //result here is false
System.out.println("!" + x + " = " + result);
result = !y; //result here is true
System.out.println("!" + y + " = " + result);
result = !(x && y); //result here is true
System.out.println("!("+ y + " && " + x + ") = " + result);
result = !(x || y); //result here is false
System.out.println("!(" + y + " || " + y + ") = " + result);
}
}

The output of the program above is:

8
MODULE OF INSTRUCTION

The Conditional Operators

Conditional operator is also called as the ternary operator because this


operator consists of three operands. The purpose of this operator is to
evaluate which value should be returned to the variable. The structure
of the expression using this operator is:

operand1?operand2:operand3

The operand1 is a Boolean expression that will be evaluated, if the


value of operand1 is true, operand2 is the value returned, otherwise
operand3 will be returned.

public class ConditionalOperatorDemo {


public static void main(String[] args) {
String result = "";
int age = 17;
result = (age >= 18) ? "qualified to Vote!" : "too young to vote!";
System.out.println(age + " is " + result);
}
}

Computer Programming 2 9
Week 3-4 Operator and Operator Precedence

The output of the program above is:

Let us discuss what happened in the program after we use the


conditional operator. The expression (age >= 18) ? "Qualified to
Vote!" : "Too young!" uses conditional operator, the first operand
here is (age >= 18) and if we evaluate this we will get the value of
false because the variable age has a value of 17 and it is not greater
than or equal to 18. Since the value of the first operand is false this
expression will return the value of operand3 which is “too young to
vote”.

Let’s try another example, this time we set the value of variable age to
19.

public class ConditionalOperatorDemo {


public static void main(String[] args) {
String result = "";
int age = 19;
result = (age >= 18) ? "qualified to Vote!" : "too young to vote!";
System.out.println(age + " is " + result);
}
}

The output of the program above is:

Bitwise and Bit Shift Operators

Bitwise and Bit Shift Operators are basically used for bit manipulation,
or using bits of an integral type value to perform bit-by-bit operation.
These operators can be applied to any integral type (long, int, short,
char and byte).

10
MODULE OF INSTRUCTION

There are three Bitwise operators in Java, these are & (Bitwise And), |
(Bitwise Inclusive Or), ^ (Bitwise Exclusive Or) and ~ (One’s
Compliment). The truth table for Bitwise operators are as follows:

A B A&B A|B A^B ~A


0 0 0 0 0 1
0 1 0 1 1 1
1 1 1 1 0 0
1 0 0 1 1 0

We will be using byte data type for all the examples in bitwise
operators, because byte can be easily represented in bits (byte is only 8
bits while other integral data types is much more than that).

 & (Bitwise And) – The result of the operation will be 1 if it


exists in both operands.
For example: 12 & 5
We need to convert both values to binary:
12 = 00001100, 5 = 00000101
Value Bit Representation
12 1 1 0 0
5 0 1 0 1
Result 0 1 0 0

The table above shows the bit computation of the example, each
bit will be computed separately using the & operator. For
example, let us execute the second row from the table 1 & 0 the
result would be 0. The result if we execute 00001100 & 00000101
expression is 00000100 or 4.

therefore: 12 & 5 = 4

Here is the example of Bitwise And in Java program:

Computer Programming 2 11
Week 3-4 Operator and Operator Precedence

The output for the program above is:

Here is the bit representation of the sample Java


program:
14 = 00001110, 5 = 00000101
Value Bit Representation
a = 14 1 1 1 0
b=5 0 1 0 1
Result 0 1 0 0
c = 00000100 or 4

 | (Bitwise Inclusive Or) – The result of the operation will be 1


if it exists in either operand.
For example: 9 | 13
We need to convert both values to binary:
9 = 00001001, 13 = 00001101
Value Bit Representation
9 1 0 0 1
13 1 1 0 1
Result 1 1 0 1

therefore: 12 | 5 = 13

Here is the example of Bitwise Inclussive Or in Java


program:

12
MODULE OF INSTRUCTION

The output for the program above is:

Here is the bit representation of the sample Java


program:
20 = 00010100, 16 = 00010000
Value Bit Representation
a = 20 1 0 1 0 0
b = 16 1 0 0 0 0
Result 1 0 1 0 0
c = 00010100 or 20

 ^ (Bitwise Exclussive Or) – The result of the operation will be


1 if both operands are different.
For example: 6 | 9
We need to convert both values to binary:
6 = 00000110, 9 = 00001001
Value Bit Representation
6 0 1 1 0
9 1 0 0 1
Result 1 1 1 1

therefore: 6 | 9 = 15

Here is the example of Bitwise Exclussive Or in Java


program:

Computer Programming 2 13
Week 3-4 Operator and Operator Precedence

The output for the program above is:

Here is the bit representation of the sample Java


program:
20 = 00010010, 17 = 00010001
Value Bit Representation
a = 18 1 0 0 1 0
b = 17 1 0 0 0 1
Result 0 0 0 1 1
c = 00000011 or 3

 ~ (Bitwise One’s Complement) – This operator is used to flip


the bits, it toggles each bit from 0 to 1 or from 1 to 0.
For example:
10001001 and if we flip the each bit it will result to
01110110.

 << (Binary Left Shift) –This operator shifts or move the left
operands value to the left by the number of bits specified in the
right operand.
For example:
00000001 << 2 = 00000100
.01010001 << 3 = 1010001000

 >> (Binary Right Shift) – This operator shifts or move the left
operands value to the right by the number of bits specified in
the right operand, filling with the highest (sign) bit on the left.
For example:
01001000 >> 3 = 00001001

14
MODULE OF INSTRUCTION

.10100001 >> 2 = 00101000


 >>> (Unsigned Right Shift Zero Fill) –This operator shifts
the left operands value to the right by the number of bits
specified in the right operand and shifted values will be filled
with zeros.
For example:
01101000 >>> 2 = 00011010
.10000001 >>> 2 = 00100000

Assignment Operators

Let us discuss first what is Assignment Statement and Assignment


Expressions.

An assignment statement is use to assign value to a variable. It uses =


(equal) operator or any assignment operators to designate a value for a
variable. The syntax for assignment statement is as follows:

<variable> = <expression>;

An expression can be a value, variable or a computation of values and


variables using operators and evaluate them to a value. For example,

m = 2; //assign value of 2 to variable m

cm = m * 100; // assign the multi to variable cm

In assignment statement, we can assign the variable to itself, for


example:

int x = 1;
x=m+1

The assignment statement x = x + 1 means, we assign the addition of x


and 1 to variable x, then the value of x becomes 2 after the statement is
executed.

In the case that we need to assign the value to a multiple variables, we


can do this:

x = y = z = 1;

Computer Programming 2 15
Week 3-4 Operator and Operator Precedence

The statement above is equivalent to:

x = 1;
y = 1;
z = 1;

Augmented Assignment Operators

Java allows you to combine arithmetic operator with assignment (=)


using Augmented Assignment Operators. The list of augment assignment
operators are as follows:

Operator Description Example


Simple assignment operator. Assigns z = x + y will
= values from right side operands to left assign value of x +
side operand. y into z
Add and assignment operator. This
operator adds right operand to the left z += 2 is equivalent
+=
operand and assign the result to left to z = z + 2
operand.
Subtract and assignment operator. This
operator subtracts right operand from z -= x is equivalent
-=
the left operand and assign the result to to z = z – x
left operand.
Multiply and assignment operator. This
operator multiplies right operand with z *= x is equivalent
*= the left operand and assign the result to to z = z * x
left operand.
Divide and assignment operator. This
operator divides left operand with the z /= 2 is equivalent
/= right operand and assign the result to to z = z / 2
left operand.
Modulus and assignment operator. This
z %= x is
operator takes modulus using two
%= equivalent to z = z
operands and assign the result to left
%x
operand.
z <<= 2 is same as
<<= Left shift and assignment operator.
z = z << 2
z >>= x is same as
>>= Right shift and assignment operator.
z = z >> x

16
MODULE OF INSTRUCTION

z &= 2 is same as z
&= Bitwise AND and assignment operator.
=z&2
Bitwise exclusive OR and assignment z ^= 2 is same as z
^= operator. =z^2
Bitwise inclusive OR and assignment z |= x is same as z =
|= operator. z|x

Precedence of Java Operators

Operator precedence determines which operators should be the first to execute.


An operator can have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator +. The
table shows the list of operators according to precedence order.

Operators Precedence
postfix expr++, expr--
++expr, --expr, +expr, -
unary
expr, ~, !
multiplicative *, /, %
additive +, -
shift <<, >>, >>>
relational <, >, <=, >=
equality ==, !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
=, +=, -=, *=, /=, %=, &=,
assignment
^=, |=, <<=, >>=, >>>=

For example:

Given a complicated expression,

z = x%2*3+b/4+9-c;

Computer Programming 2 17
Week 3-4 Operator and Operator Precedence

we can re-write the expression and place some parenthesis base on operator
precedence,

z = ((x%2) *3) + (b/4) + 9 - c;

18

You might also like