Lecture 5
Operators
and Expressions
Read on for an overview of
operators, expression, precedence and order of expression evaluation and type
conversion..
Operators
& Operands
Expressions
Operators and Operands
We know that
variables can be assigned values once they are declared. We can also
modify the value a variable holds at any time later in the program.
Consider the following:-
int
x = 10;
x
= 5;
The variable x
was declared and assigned a value of 10. Later, x is assigned a new
value of 5. Variables have only one value — the
current one.
The general form of
an assignment statement is:
variable = expression.
Really,
the assignment operator = does not mean ‘is equal to’ in the algebraic sense. You should imagine it as meaning
‘becomes’ or ‘set’. Thus, x
= 5 means x is set to a value of 5.
You
should know the meaning of operator and operand. In the
statement x = 5, the operator is = and the
operands are x and 5.
Let's
look at some more assignment operators.
Assignment
Operators
Here
are some more assignment statements.
int
x;
int
y;
x
= 6; //assign the literal
value of 6 to x
y
= x; //assign the value held
by the variable x to y
The
following is a common sort of operation.
x
= x + 2; // x is assigned a new value of 8
The
variable x is re-assigned the value it currently holds added to the number
2. In other words - add the number 2 to the value of x and re-assign
this new number to x.
Here
are a few more examples of a similar kind.
x
= 6;
x
= x - 2; //x is assigned a new value of 4. I.e. 6 -
2
x
= x * 2; //x is assigned a new value of 8. I.e. 4 *
2
x
= x / 2; //x is assigned a new value of 4. I.e. 8 /
2
x
= x % 2; //x is assigned a new value of 0. I.e. 4 %
2 leaves a remainder of 0
The
table below shows there are shorthand operators for these 5 operations.
Instead of typing:-
x
= x + 2;
I
can type:-
x
+= 2;
Which
produces the same result. A complete list of assignment operators is
shown in the table below.
Operator |
Name |
Example/Description |
= |
assignment |
x
= 10; //put the value of 10 into x x
= y; //put the value of y into x |
+=
|
assignment with addition |
i +=10; //shorthand for i = i+10 |
-= |
assignment with subtraction |
i -=10; //shorthand for i = i-10 |
*= |
assignment with multiplication |
i *=10; //shorthand for i
= i*10 |
/= |
assignment with division |
i /=10; //shorthand for i
= i/10 |
%= |
assignment with modulo
division |
rem
%=10; //shorthand for rem = rem%10 |
~Now
try the activity~
Activity A |
-
Determine the values of x and y at the end
of the code fragment
int x
= 10, y = 5;
x +=
2;
y *=
x;
- Determine the values of p and q at the end of the code
fragment
int p
= 10, q = 16;
p
-= 2;
q
/= p;
Why not check your answers
by using code.
|
Arithmetic
Operators
The
arithmetic operators are listed below.
Operator |
Name |
Example/Description |
+
|
addition |
x = y + 4;
//put the value of y plus 4 into x |
-
|
subtraction |
x = y - 4; //put the value of
y minus 4 into x |
*
|
multiplication |
x = y * 4; //put the value of
y times 4 into x |
/
|
division |
x = y / 4; //put the value of
y divide by 4 into x |
%
|
modulo (remainder) |
x = y %
4; //put the value of the remainder of y divided by 4 into x |
You
should note that the effect of division in Java is not always the same as
arithmetic division when using integers. For example:-
10
/ 4 will give the integer result 2
int
x = 10;
x
/ 4 will also give the integer result 2
If
any of the operands are real, the result will be real;-
10.0
/ 4 will give the real result 2.25
int
x = 10.0;
x
/ 4 will also give the real result 2.25
Warning:
do NOT attempt to divide by zero; this will cause an error.
~Now
try the activity~
Activity B |
-
Determine the values of x and y at the end
of the code fragment
int x
= 10, y = 5;
x = y
+ 2;
y = x
+ 4;
- Determine the values of p and q at the end of the code
fragment
int p
= 10, q = 5;
p
= 4 - q;
q
= 4 / p;
- Determine the values of rem at the end of the code
fragment
int
rem = 6 % 4;
Why not check your answers
by using code.
|
Increment/Decrement
Operators
Some time ago a large number of
programs were studied, and statements of the form
int
n = 5;
n = n
+ 1;
were
found to be extremely common. The n on the left-hand side of the = is
assigned a new value using the current value of n, incremented by 1, in
this case resulting in 6.
Thus
something = something + 1;
and
something = something
- 1;
were found to be
such a common instructions that many programming languages including Java
created a
shorthand version of this increment or decrement instruction
The
shorthand increment version is written as:
The
shorthand decrement version is written as:
The
table below shows the increment/decrement operators.
Operator |
Name |
Example/Description |
++
|
increment before |
++j;
//increment j by 1 before using k
= ++j; //increment j by 1 before assigning the value to k |
++
|
increment after |
k
= j++; //increment j by 1 after assigning the value of j to
k |
-- |
decrement before |
--j;
//decrement j by 1 before using k
= --j; //decrement j by 1 before assigning the value to k |
-- |
decrement after |
k
= j--; //decrement j by 1 after assigning the value of j to
k |
We
can see from the table that the increment and decrement operators can be
positioned before or after a value or variable. To understand the
different results from this positioning let's look at a few examples.
Increment
example
int
count = 10;
count
= count + 1; //Increment count by 1. Result is count holds a value of
11
Alternative
count++;
//Increment count by 1
Decrement
example
int
count = 10;
count
= count - 1; //decrement count by 1. Result is count holds a
value of 9
Alternative
count++;
//decrement count by 1
Now,
the position of the increment/decrement operators can be important in
an expression.
When
++ follows the variable (e.g. count++) incrementation happens last.
This is called post-incrementing. When ++ comes before the
variable (e.g. ++count) incrementation happens last. This is called pre-incrementing.
Post-increment
example
int
k = 10, ans;
ans
= k++;
The
value of k is assigned to ans first. Then k is incremented. So
ans now has a value of 10 and k has a value of 11.
Pre-increment
example
int
k = 10, ans;
ans
= ++k;
First
k is incremented. Then the value of k is assigned to ans. So ans
now has a value of 11 and k has a value of 11.
The
same principles apply to the decrement operator -- only we would call it post-decrementing
and pre-decrementing.
~Now
try the activity~
Activity C |
-
Determine the values of ans and count at
the end of the code fragment
int
ans = 1, count = 2;
ans
+= count++;
- Determine the values of p and q at the end of the code
fragment
int p
= 10, q = 5;
p
= ++q + 3;
- Determine the values of x and y at the end of the code
fragment
int x
= 2, y = 5;
y
+= 3;
x *=
y--;
Why not check
your answers by using code. |
Expressions
An expression in Java is a combination of
operators and operands (variables, literal values and method calls.) In the expression
a = b + c;
a, b and c are variables (or operands) and = and +
are operators. Since an expression can contain an unlimited number of
operators in any order, you have to be aware of both operator
associativity, precedence and order of expression evaluation.
Associativity
If all the operators
are the same then the rule is simple - all the arithmetic operators associate
left to right. Consider the following:-
a = b +
c + d;
In calculating the
value on the right of the = operator, b + c is calculated first, then d is added
to the result.
Here are a few more.
vol
= length * height * depth;
result
= x / y / z;
In the first case,
although the expression (length * height * depth) is evaluated from left to
right you would get the same answer even if you could change this associative
order (which you can't). In the second case you would get an incorrect
answer if somehow the associative order could be changed.
To see this,
consider the correct equivalent of x / y / z using parenthesis:-
result
= ( x / y) / z;
If you assumed the
following was equivalent you would be incorrect.
result
= x / (y / z);
Try giving values to
x, y, z. Say x = 10, y = 5 and z = 2. Then
result
= x / y / z; is equivalent to (10/5)/2 which is 1,
not 10/(5/2) = 4
Precedence & Order of Evaluation
What happens if the
operators in an expression are not all the same type, but are a
mixture? The associative rule doesn't apply. In mathematics, if
you write A+B*C you would first multiply B by C and then add A. Thus,
the multiplication operator takes precedence over the addition
operator. In fact, the operators * and / take precedence over + and
-. The same precedence rules are applied in Java.
Here are some
examples...
3 + 4 * 2
results in 11
3 - 4 / 2
results in 1
3 + 4 * 2 - 5
results in 6
It is often better
to use parenthesis to make sure that expressions are evaluated in the order
we wish and to make our code clearer. Parenthesis take the highest
precedence. Any expression in parentheses is evaluated first.
Let's re-write the
examples above using parentheses.
3 + ( 4 * 2)
results in 11
3 - (4 / 2)
results in 1
3 + (4 * 2) - 5
results in 6
I can force a
change in the natural precedence order. The expression:-
3 + 4 * 2
results in 11
is equivalent to
3 + ( 4 * 2)
results in 11
but I could force a
change in the precedence order by moving the parentheses:-
(3 +
4 )* 2 results in 14
~Now
try the activity~
Activity D |
Determine the result of each of the
following expressions.
-
6 + 3 * 4 /
2
-
(6 + 3) * 4 /
2
-
-5 * 4 - 6 /
2
-
-5 * (4 - 6) /
2
Why not check your answers
by using code.
|
Type
Conversion
What happens if we have an expression with
different data types involved? e.g.
float x;
int y = 5;
x = y;
What will be the resulting value of x?
Will it be 5 or a floating point version of 5, say 5.0.
In fact x would end up with a floating point
version of 5. In this case, Java automatically converts the integer value
of 5 to a floating point value of 5.0.
As we will see, Java will carry out automatic
type conversion in some cases. If we specifically need to convert values from one type to
another we can force a type conversion.
Let's look at automatic conversion and then
how to force a type conversion.
Automatic
type conversion
Automatic
type conversion means that we can copy a weaker data type to a stronger one,
such as an int to a float and a float to a double without having to think
about it. Java automatically does the conversion for us.
Consider:-
int
x = 4;
double
y;
y =
x;
Then
x would have the value of 4 but y would have the value of 4.0.
Instead of assigning an integer 4 to y, the 4 is converted to a double and then
assigned to y because y is expecting to hold a double data type and not an
integer.
Java
will carry out type conversion automatically for us as long as the
conversion is from a weaker type to a stronger type.
byte
short int
long float
double
|
|
Weakest
|
Strongest
|
However,
trying to convert from a stronger to a weaker type, such as...
int
x;
double
y = 3.2;
x =
y;
...would
result in an error message from the compiler;-
incompatible
type for...
because
we are trying to get x, which was expecting to hold an integer data type to hold
a floating point value. In some cases weaker types have not been allocated
enough memory to hold stronger types. In the case above x has been
allocated four bytes of memory but a double requires 8 bytes.
Let's
have a few more examples of valid conversions.
int
to a float
int
a = 5;
float
b;
b
= a;
Results
in b holding a value 5 in floating point format
float
to a double
float
b = 10.3;
double
c;
c
= b;
Results
in c holding a value 10.3 in double format
Numeric
type to a string
int
age = 80;
g.drawString(“My
age is is “
+ age, 5, 5); // displays "My age is
80"
In Java, when + operates on a string and a number, the
number is converted to a sequence of characters, and is then joined onto the string. The
complete string is then displayed.
Complicated
expressions
What
happens if an expression contains lots of different types?
Consider
the following expression with three different data types:-
int
a = 5;
double
c;
c
= a + 3.14F //F forces 3.14 to be considered a
float
In
order to evaluate this expression, Java requires that all the data types are
the same. The rule is simple: all values in an expression are
converted to the strongest data type. So in the expression
above, the value of a is converted to a float which is then added to
3.14. The result is then converted to a double and assigned to c.
Forcing
type conversion
What
if we specifically need to convert values from stronger type to a
weaker. We have seen that an error message will result if we try to get
Java to automatically do this for us. So, how can we can force a
type conversion?
We
must cast the stronger type to a weaker type by using expression such
as:-
(int)
forces conversion to an int
(float)
forces conversion to a float
(double)
forces conversion to a double
(char)
forces conversion to a char
Here
is an example:-
float
to an int
int
x;
double
y = 3.2;
x
= (int) y;
The
(int) in parentheses forces the conversion. Now we don't get an
error message. In effect, by using the casting statement we are
informing Java that we are intentionally converting a stronger type to
a weaker and we are not just being idiots.
We
should be aware that information can be lost when we force type
conversions. In the above example, the decimal
places are truncated: x ends up with a value of 3.
numeric
to char
We
can force conversion of a numeric type to a char by casting it,
e.g..
char
ch = (char) 65; // 65 is converted to an 'A' which is then
assigned to ch
char
ch = (char) 66; //66 is converted to a 'B' which is then assigned to
ch
Java
uses the Unicode values to convert numbers to characters. In the above
example, the Unicode value of 'A' is 65 and 'B' is 66, 'C' is 67 and so on
through to 90 for 'Z'.
~Now
try the activity~
Activity E |
Given the declaration
byte b1, b2 = 65;
int i, j = 1000;
float f1, f2 = 5.2F;
char ch;
For each of the following, state the final
type and value of the operand on the left side of the =.
-
b1 = b2 + 1;
-
i = j + b2;
-
f1 = (int) f2 +
10;
-
i
= (int) f2 * (byte)10.34;
-
ch = (char) (b2 +
3);
Why not check your answers
by using code. |
That is folks!!
Now try the Operators
& Expressions exercise
|