Ch. 2 - Lecture5 - Arithmetic Expressions and Data Conversion
Ch. 2 - Lecture5 - Arithmetic Expressions and Data Conversion
Arithmetic operations
Binary operations
Addition(+), Subtraction(-), multiplication(*), Division(/)
Remainder(%)
Example: 17%4 = 1, 3%8 = 8
a + b + c + d + e a + b * c - d / e
1 2 3 4 3 1 4 2
a / (b + c) - d % e
2 1 4 3
a / (b * (c + (d - e)))
4 3 2 1
Assignment revisited
The assignment operator
Has a lower precedence than arithmetic operators
count = count + 1;
9
Fahrenheit Celsius 32
5
See TempConverter.java
Increment and decrement a
variable
There are three ways
To increment or decrement a variable, it may appear
On both the left-hand side and the right-hand side
count = count +1; or count = count – 1;
In a larger expression
they can yield different results
Total = count++;
Total = ++count;
Assignment operators: main
idea
Often we perform
An operation on a variable, and then
For instance
num += count; num = num + count;
Assignment operators
Many assignment operators are defined in JAVA
+= performs addition
Total += 5; is equivalent to Total = Total + 5;
-= performs subtraction
result -= a + b; <=> result = result – (a + b);
/= performs division
highest /= 4; <=> highest = highest/4;
*= performs multiplication
Behavior of assignment
operators
The behavior of some assignment operators
Depends on the types of the operands
For example
in a particular situation we may want to treat
An integer as a floating point value
These conversions
Do not change the type of a variable
nor the value stored in it
Promotion
When operators need to modify their operands
Casting
The most general form of conversion
Assignment conversion
Assignment conversion occurs
When a value of one type
is assigned to a variable of another type
a JAVA operator
Specified by a type name in parentheses: (float) for instance
To cast
The type is put in parentheses in front of the value
Being converted
Conversion using casting
(cont’d)
It is helpful
To treat a value temporarily as another type