You are on page 1of 11

Fundamentals of the Java Programming Language

Lesson IV

Property of Airos Education


Copyright 2018 Airos Education
www.airos.co.za
Lesson IV (part 1): Operators and Precedence

In the previous lesson, we discussed how to create variables of different data types (such as
string, integer, and double) and we were able to print out those variables using the println( )
function. However, printing to the screen is not all we can do with variables. If we wish, we
can manipulate the contents of those variables. This is where operators come in. Operators
are special symbols that allow us to manipulate data or operands (the value that the operator
operates on) by carrying out logical and/or arithmetic calculations. These operators are put
together with variables and statements in a logical order to build complex applications.
Objectives of Lesson IV

❖ To understand Java operators


❖ To understand how to use operators to manipulate the contents of variables
❖ To understand operator precedence and associativity

Section A: Operators

Java includes many different types of operators such as, arithmetic operators. assignment
operators, comparison operators, logical operators, identity operators, membership
operators, and bitwise operators. All of these operators have varying capabilities and allow
you, as a programmer, to build efficient and complex functions.

Arithmetic Operators

In programming, we are able to compute mathematical calculations, such as, 1 + 1 or 2 * 5,


and this is accomplished using mathematical operators. Mathematical (or numerical
operators) include the standard arithmetic operators that are used in algebra, as table 1
indicates:

Operator Meaning Example Result

+ Addition 1+2 3

- Subtraction 2-1 1

* Multiplication 2*2 4

/ Division 4/4 1

% Divides the value on 5%2 1


the left by the value
on the right, and
returns the
remainder

Property of Airos Education


Copyright 2018 Airos Education
www.airos.co.za
1
++ Increment (increases 1++ 2
the value of the
operand by 1)

-- Decrement 2-- 1
(decreases the value
of the operand by 1)

Table 1: Arithmetic operators

The addition, subtraction, multiplication, and division operators are fairly straight sword, and
be programmatically used as follows:

System​.​out​.​println​(​5​ ​+​ ​2​);​ ​//prints 7


System​.​out​.​println​(​25​ ​-​ ​13​);​ ​//prints 12
System​.​out​.​println​(​5​ ​*​ ​6​);​ ​//prints 30
System​.​out​.​println​(​12​ ​/​ ​3​);​ ​//prints 4

To perform these operations on variables, we can simply declare our variables, and
subsequently use them as follows:

int​ num1 ​=​ 1​ 0;


int​ num2 =​ ​ 6​ ;

System​.​out​.​println​(​num1 ​+​ num2​);​ ​//prints 16


System​.​out​.​println​(​num1 ​ ​
- num2​);​ ​//prints 4
System​.​out​.​println​(​num1 ​ ​
* num2​);​ ​//prints 60
System​.​out​.​println​(​num1 ​ ​
/ num2​);​ ​//prints 1

As you’ve probably noticed from the division operation, the result of 10 divided by 6 is 1 and
not 1.6. This is because when two variables are of type integer, the division of those integers
will result in the quotient with the fraction part truncated. Thus, to perform a float point
division, one of the operands must be a floating-point number. For example, 5.0 / 2 = 2.5.

The remaining arithmetic operators are the % (referred to as modulus), ++ (increment), and
-- (decrement). The % operator yields the remainder after the division of two operands. The
operator on the left is the dividend and the operator on the right is the divisor. For example, 4
% 2, will be equal to 0, and not 2, because the modulus operator returns the remainder of
the division. The modulus operator is often used to check if a number is even or odd, as any
number divided by 2 will have a remainder of 0 if the number is even. On the other hand, the
increment and decrement only requires one operand. The increment operator increases the
value of the operand by 1, whereas the decrement operator decreases the value of the
operand by 1:

System​.​out​.​println​(++​2​);​ /
​ /prints 3
System​.​out​.​println​(--​3​);​ /​ /prints 2

As you can see, numerical operators are a valuable asset in programming as they can be
used to create calculators or, as mentioned, determine if a number is odd or even, however,
this is far from the limits of operators and programming. Programs are capable of comparing

Property of Airos Education


Copyright 2018 Airos Education
www.airos.co.za
2
variables, identifying relationships and making decisions based on the data it has been
given. We can harness this power through the use of operators and conditional constructs.

Comparison Operators

A comparison operator can be used to compare two variables and identify if there is a
relationship between them. These operators (also referred to as relational operators)
compares two expressions and returns a boolean value. They can be used to determine if a
variable is greater than, less than, equal to, or not equal to another variable:

Operator Meaning true false

> Greater than 13 > 2 2 > 13

>= Greater than or 3 >= 2 2 >= 3


equal to

< Less than 2 < 13 2<2

<= Less than or equal 2 <= 2 3 <= 2


to

== Equal to 5 == 5 5 == 6

!= Not equal to 3 != 2 2 != 2
Table 2: Comparison/relational operators

The following demonstrates sample usage of relational operators:

public​ ​class​ ​RelationalExample​ {

public​ ​static​ ​void​ main​(​String​[]​ args​)​ {

int​ a ​=​ 5 ​ ;
int​ b =​ ​ 7 ​ ;
int​ c = ​ ​ 7 ​ ;

System​.​out​.​println​(​"a > b = "​ ​+​ ​(​a ​>​ b​)); // returns false


System​.​out​.​println​(​"a < b = "​ ​+​ ​(​a ​<​ b​)); // returns true
System​.​out​.​println​(​"k == b = "​ ​+​ ​(​c ​==​ b​));​ ​// returns true
System​.​out​.​println​(​"k != b = "​ ​+​ ​(​c ​!=​ b​)); // returns false
}
}

Property of Airos Education


Copyright 2018 Airos Education
www.airos.co.za
3
Logical Operators
Logical operators are used to compare statements and develop relationships. These
relationships are more extensive and used to make complex decisions. The symbols for
logical operators are as follows:

Operator Meaning Example

&& (logical and) True if both statements are x && y


true

|| (logical or) True if either statement is x || y


true

! (logical not) True if the statement is false !x


Table 3: Logical operators

Note: Logical operators will become much more clear when we learn how to use conditional
statements. For now, all you need to know is that these type of operators exist in Java.

Bitwise and Bit Shift Operators

In Java, there are four bitwise and three bit shift operators. These type of operators are used
on integral types, such as, long, int, byte, and short to perform bit-level operations.

1. Bitwise OR (symbol: |): This is a binary operator, which means it requires two
operands. The bitwise OR operator compares the corresponding bits of the two
operands, and if either of the bits is equal to 1, then it returns 1, but if both bits are
zero, then it returns zero. For example, consider the numbers 12 and 25. In binary,
these numbers will be 00001100 and 00011001, respectively.

Note: a bit is a single binary value - either zero or one. The numbers 12 and 25
consist of 8 bits.

So, the first bit for both 12 and 25 are zero in this case, hence the bitwise operator
will return zero. The second bit is also zero for both, hence it will return zero again.
However, the fourth bit differ for both numbers, 12 is zero and 25 is one. In this case,
the bitwise operator will return one. This goes on until the last bit is compared for
both numbers, and the resulting bits for the comparison of 12 and 25 will be
00011101 (which is equal to 29).

int​ twelve ​=​ ​12;


int​ twentyFive ​=​ ​25;

System​.​out​.​println​(​twelve ​|​ twentyFive​);​ ​//prints 29

2. Bitwise AND (symbol: &): Similarly to the bitwise OR, the bitwise AND is also a binary
operator that compares corresponding bits of two operands. However, the bitwise
AND operator returns one only if both bits are equal to one, otherwise it returns zero.

Property of Airos Education


Copyright 2018 Airos Education
www.airos.co.za
4
For example, the comparison of 12 and 25 will return 00001000 (which is equal to 8).
This because only the fifth bit of both these numbers are equal to one, hence it will
return one only for that bit - the rest will be zero.

System​.​out​.​println​(​twelve ​|​ twentyFive​);​ ​//prints 8

3. Bitwise Complement (symbol: ~): This is unary operator, which means that it only
requires one operand. This operator inverts the bit pattern i.e. it converts every zero
into a one, and vice versa. For example, the number 35 in binary is 00100011, hence
the inversion of the pattern will be 11011100, which equals to 220. However,
consider the following result:

System​.​out​.​println​(~​35​);​ ​//prints -36

So, why is the result -36 instead of 220? Well, it is because the bitwise complement
returns the negative notation of the operand (35). Negative notation (also known as
2’s complement) is calculated as follows: -(n+1), where n is the number. Hence, the
equation after the number is inverted will be -(00100011+1), which is equal to
-00100100 (-36).

4. Bitwise XOR (symbol: ^): The bitwise xor operands compares the corresponding bits
of two numbers. If the bits are different, it returns 1, and if the bits are the same it
returns 0. So, compare the following two numbers:

12 (00001100)
25 (00011001)

As you can see, the first bit of the two numbers are the same, hence 0 will be
returned. The same applies for the second and third bit of both numbers. However,
the fourth bit of both numbers is different i.e. for 12, the bit is 0, and for 25, the bit is
1, hence 1 will be returned. The same logic applies to the remaining numbers, and
the result will be 00010101, which is equal to 21:

System​.​out​.​println​(12^​25​);​ ​//prints 21

5. Left Shift (symbol: <<): The left shift operator simply shifts the bit pattern of the
operand to the left by a specified number of bits:

212 (11010100) << 1 will evaluate to 110101000 (424) - shifted by 1


212 (11010100) << 0 will evaluate to 11010100 (212) shifted by 0
212 (11010100) << 4 will evaluate to 110101000000 (3392) shifted by 4

System​.​out​.​println​(​212​<<​1​);​ /
​ /prints 424
System​.​out​.​println​(​212​<<​0​);​ /​ /prints 212
System​.​out​.​println​(​212​<<​4​);​ / ​ /prints 3392

6. Right Shift (symbol: >>): The right shift operator simply shifts the bit pattern of the
operand to the right by a specified number of bits:

Property of Airos Education


Copyright 2018 Airos Education
www.airos.co.za
5
212 >> 1 will evaluate to 01101010 (106) - shifted by 1
212 >> 0 will evaluate to 11010100 (212) - shifted by 0
212 >> 8 will evaluate to 00000000 (0) - shifted by 8

System​.​out​.​println​(​212​>>​1​);​ /
​ /prints 106
System​.​out​.​println​(​212​>>​0​);​ /​ /prints 212
System​.​out​.​println​(​212​>>​8​);​ / ​ /prints 0

Note: If the number is a 2's complement signed number, the sign bit is shifted into the
high-order positions.

7. Unsigned Right Shift (symbol: >>>): The unsigned right shift operator shifts zero into
the leftmost position: For example, compare the output of the following statements:

int​ num ​=​ ​-​5​;

System​.​out​.​println​(​num >
​ >​ ​1​);​ ​//signed right shift prints -3
System​.​out​.​println​(​num >​ >>​ ​1​);​ ​//unsigned right shift prints 2147483645

Assignment Operators

Up until now, we have been assigning values to variables using the assignment operator (=)
i.e. the equal sign:

int​ age ​=​ ​34;

However, the equal sign can be compounded with the arithmetic operators and can add to
an existing variable. This is similar to adding two variables together, but in a more efficient
manner. For example:

int​ age ​=​ ​34;


age ​+=​ 2
System.out.println​(​age​);​ ​//prints 36

In the example, we used an ​addition assignment operator ​and this is equivalent to doing
the following:

int​ age ​=​ ​34;​ ​//declare variable age and initialise with value 34
age ​=​ age ​+​ ​2;​ ​//re-assign a value to one, which is the old value of one + 2
System.out.println​(​age​);​ ​//prints 36

The remaining combinations of the assignment operator and the arithmetic operators are as
follows:

Operator Meaning Example Equivalent to Result

= Equals to x = 1.3 x = 1.3 1.3

+= Add assignment x += 1 x=x+1 2.3

Property of Airos Education


Copyright 2018 Airos Education
www.airos.co.za
6
-= Subtraction x -= 1 x=x-1 0.3
assignment

*= Multiplication x *= 1 x=x*1 1.3


assignment

/= Float division x /= 1 x=x/1 1.3


assignment

%= Remainder x %=1 x=x%1 0.30


assignment

<<= Left shift AND (assume x = 1) x = x << 1 2


assignment x <<= 1

>>= Right shift AND (assume x = 1) x = x >> 1 0


assignment x >>= 1
operator

&= Bitwise AND (assume x = 1) x=x&1 1


assignment x &= 1

^= Bitwise XOR (assume x = 1) x=x^1 0


assignment x ^= 1

|= Bitwise OR (assume x = 1) x=x|1 1


assignment x |= 1

Table 4: Assignment operators

Section B: Operator Precedence and Associativity

Similarly to mathematics, precedence exists in Java. If you recall from primary school
mathematics, you were taught to use the BODMAS (Brackets, Orders, Division,
Multiplication, Addition, and Subtraction) rule, which determined the order in which you
calculated the answer of sums.

Property of Airos Education


Copyright 2018 Airos Education
www.airos.co.za
7
Figure 1: The BODMAS rule

Likewise, in Java, certain operators are executed or take priority over others. This simply
means that by using certain operators with segments of code, that code will be computed
before or after the rest of the code in the statement according to it hierarchical standings.

Category Operator

Parentheses ( ), [ ]

Increment, decrement, logical not, bitwise ++, - -, !, ~


complement

Multiplication and Division *, /

Addition and Subtraction +, -

Shift >>>, >>>, <<

Relational >>, >=, <, <=

Equality ==, !=

Bitwise AND &

Bitwise XOR >^

Bitwise OR |

Logical AND &&

Logical OR ||

Ternary operator (discussed in lesson VI) ?:

Assignment >=, +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=
Table 5: The level of precedence of Java operators

Property of Airos Education


Copyright 2018 Airos Education
www.airos.co.za
8
For example, given the following mathematical expression, how do you think it will be
evaluated?

(​3​ ​+​ ​4​ ​*​ x​)​ ​/​ ​5​ ​–​ ​10​ ​*​ ​(​y ​-​ ​5​)​ ​*​ ​(​a ​+​ b ​+​ c​)​ ​/​ x ​+​9​ ​*​ ​(​4​ ​/​ x ​+​ ​(​9​ ​+​ x​)​ ​/​ y)

Well, although Java has its own way to evaluate an expression, the results of a Java
expression and its corresponding arithmetic expression are the same. Therefore, you can
apply the arithmetic rules for evaluating a Java expression. Operators contained within pairs
of parentheses are evaluated first. Parentheses can be ​nested​, in which case the
expression in the inner parentheses is evaluated first. When more than one operator is used
in an expression, then the table 5 can be used to determine the order of evaluation.

Note: If the operators have the same precedence, then the operators are simply evaluated
from left to right, except for the ternary operator, assignment operators, and the increment,
decrement, logical not, and bitwise complement operators, which are evaluated from right to
left. This is referred to as ​associativity​.

Property of Airos Education


Copyright 2018 Airos Education
www.airos.co.za
9
Formative Assessment

1. Explain how parentheses can be used to override operator precedence and give an
example.
2. In your own words, explain the difference between the bitwise OR and the bitwise
AND operators.
3. Create a new class called ​Concat​.
a. In the main( ) method, declare and initialise two variables of type string.
b. Print out both strings.
c. Subsequently, concatenate both strings using the addition operator and print
out the result.
d. Next, declare and initialise two variables of type int.
e. Increment one and decrement the other, while simultaneously printing out the
result.

Property of Airos Education


Copyright 2018 Airos Education
www.airos.co.za
10

You might also like