07 April 2003 This lecture covers the reading in Chapter 4: Operators |
Review of Session 3 Homework |
Note: Line 37 uses the equals method that all
string object inherit to enable you to compare the contents of two strings:
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/String.html#equals(java.lang.Object)
Note: Line 43 uses the doubleValue method of
the Number object,
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Number.html#doubleValue()
which comes as part of the lang package: the
package you do not need to import becauses it is always available to the
compiler.
Let us look at the following:
The do while statement
guarantees that your code executes (do) until something you specifies happens
(while).
In the program above, it guarantees that the user sees choices (line 34) and can
quit the program (line 54).
Unlike the for loop, the
do loop has no pre-set number of
iterations (and therefore do not need to initialize and increment a counter).
Indeed, the program above has a potentially infinite loop: if the user never
quits, the program never stops.
A detail explanation of both do
and do while is:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/while.html
What applications can we think of for such infinite loops?
http://java.sun.com/j2se/1.4.1/docs/api/java/io/package-summary.html
provides the BufferedReader class: http://java.sun.com/j2se/1.4.1/docs/api/java/io/BufferedReader.html
and the InputStreamReader class: http://java.sun.com/j2se/1.4.1/docs/api/java/io/InputStreamReader.html
Note: Line 29 "wraps" the input stream reader object, isr, in a buffered reader object, bf.
http://java.sun.com/j2se/1.4.1/docs/api/java/text/package-summary.html
Note: The java.text package provides the
NumberFormat class, which is abstract enough to work with numbers of any
format.
For example, in some locales, commas and periods are reversed: 10.000,02 instead
of 10,000.02
This is a case where Java supports polymorphism: many forms or formats.
http://java.sun.com/j2se/1.4.1/docs/api/java/text/NumberFormat.html
The text package also provides the DecimalFormat class:
http://java.sun.com/j2se/1.4.1/docs/api/java/text/DecimalFormat.html,
which has the parse method:
http://java.sun.com/j2se/1.4.1/docs/api/java/text/DecimalFormat.html#parse(java.lang.String,
java.text.ParsePosition)
used on line 42.
An error is an object, so we will wait until we cover objects and class in session 6, when we do cover error handling.
In the language of programming (and mathematics), we say that operators
operate on operands.
In the case of sum = cost1 + cost2
for example, the operators are the addition operator (+)
and the assignment operator (=). The operands
are that on which the operators operate, namely, the variables cost1,
cost2, and sum.
If you write a Java statement such as:
int totalDaysInYear = 365;
The assignment operator (=) assigns the integer value of 365 to the
variable named totalDaysInYear.
Point location = new Point(4,3);
The assignment operator (=) assigns x- and y-coordinate values.
The new operator creates a new instance of a
class and returns a reference to that instance.
Numbers are represented in memory using bits. A bit is the smallest unit that
a computer can work with.
A bit has two possible values, 0 or 1.
Everything in a computer is represented using different numbers of bits.
A number is represented by a series of bits which represent different powers of
2.
An 8 bit number (byte):
Value of the number | Bits |
0 | 00000000 = (0*2^0) |
1 | 00000001 = (1*2^0) |
4 = 4 + 0 + 0 | 00000100 = (1*2^2) + (0*2^1) + 0^0 |
8 = 8 + 0 + 0 + 0 | 00001000 = (1*2^3) + (0*2^2) + (0*0^1) + 0^0 |
13 = 8 + 4 + 1 | 00001101 = (1*2^3) + (1*2^2) + (1*0^1) + 2^0 |
255 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 | 11111111 = ... |
Operator | Name | Use | Description |
---|---|---|---|
+ |
addition | op1 + op2 |
Adds op1 and op2 |
- |
subtraction |
op1 - op2 |
Subtracts op2 from op1 |
* |
multiplication | op1 * op2 |
Multiplies op1 by op2 |
/ |
division | op1 / op2 |
Divides op1 by op2 |
% |
modulus (or mod) | op1 % op2 |
Computes the remainder of dividing op1 by op2 |
The arithmetic operators return a number.
numeric return value = <operand1> <operator> <operand2>; example: myLongString = myShortString + myOtherString;
Example of modulus:
The output is:
4 divided by 12 = 0 with a remainder of 4, so modulus is 12 divided by 4 = 3 with no remainder, so modulus is: 0
Arithmetic operators:
How many binary operators are there in the following application?
class Weather { public static void main(String[] arguments) { float fah = 86; System.out.println(fah); // To convert Fahrenheit into Celsius // Begin by subtracting 32 fah = fah - 32; // Divide the answer by 9 fah = fah / 9; // Multiply that answer by 5 fah = fah * 5; System.out.println(fah); float cel = 33; System.out.println(cel); // To convert Celsius into Fahrenheit // Begin by multiplying it by 9 cel = cel * 9; // Divide the answer by 5 cel = cel / 5; // Add 32 to the answer cel = cel + 32; System.out.println(cel); } }
The unary minus operator ( - ) operates on a single operand and converts a positive value into a negative value.
How about this case? What will be the value of y?
The println method will return the value of y that results from line t, which uses the unary minus operator on a negative operand.
++expr
--expr
~ bitwise unary NOT (unimportant for this course)
! logical unary NOT
!(false) = true; // complement of 'false' is 'true'
!(true) = false; // complement of 'true' is 'false'
I think we can say that a loop counter,
such as i++, only operates on one operand.
Here's some handy shortcuts:
x += y; // x = x + y
x -= y // x = x - y
x *= y; // x = x * y
x /= y; // x = x / y
Here's some more complete reference tables:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/opsummary.html#assignment
Operator | Use | Equivalent to |
---|---|---|
+= |
op1 += op2 |
op1 = op1 + op2 |
-= |
op1 -= op2 |
op1 = op1 - op2 |
*= |
op1 *= op2 |
op1 = op1 * op2 |
/= |
op1 /= op2 |
op1 = op1 / op2 |
%= |
op1 %= op2 |
op1 = op1 % op2 |
&= |
op1 &= op2 |
op1 = op1 & op2 |
|= |
op1 |= op2 |
op1 = op1 | op2 |
^= |
op1 ^= op2 |
op1 = op1 ^ op2 |
<<= |
op1 <<= op2 |
op1 = op1 << op2 |
>>= |
op1 >>= op2 |
op1 = op1 >> op2 |
>>>= |
op1 >>>= op2 |
op1 = op1 >>> op2 |
Operator | Use | Description |
---|---|---|
?: |
op1 ? op2 : op3 |
If op1 is true, returns op2 . Otherwise,
returns op3 . (This is the
conditional operator.) |
[]
| type []
| Declares an array of unknown length, which contains type elements. |
[]
| type[ op1 ]
| Creates and array with op1 elements. Must be used with
the new operator. |
[]
| op1[ op2 ]
| Accesses the element at op2 index within the array op1 .
Indices begin at 0 and extend through the length of the array minus one. |
.
| op1.op2
| Is a reference to the op2 member of op1 . |
()
| op1(params)
| Declares or calls the method named op1 with the specified
parameters. The list of parameters can be an empty list. The list is
comma-separated. |
(type)
| (type) op1
| Casts (converts) op1 to type . An exception will be thrown
if the type of op1 is incompatible with type . |
new
| new op1
| Creates a new object or array. op1 is either a call to a
constructor, or an array specification. |
instanceof
| op1 instanceof op2
| Returns true if op1 is an instance of op2 |
Example of the conditional operator:
The output is:
100 is greater than 99, so max is: 100 101 is greater than 99, so max is: 101
Does the conditional operator remind you of a control statement that you
already know?
Let's write the equivalent logic using keywords that depend on conditions.
Can be useful in specialized circumstances. Not a focus of this course.
An operator
that manipulates the bits of one or more operands both individually and in
parallel, for example, unary one's complement operator (~
), binary
logical operators (&
, |
, ^
), binary shift
operators (<<
, >>
, >>>
).
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/bitwise.html
Logical operators test a condition by comparing values and return a boolean value (true or false).
Here's two comparison operators in a sequence:
isBigSum = sum > 100;
The variable isBigSum gets the value true only if the sum is
greater than 100.
Note: Do not confuse the two forward slashes of comments (//) with the two "pipes" of one of the logical operators (||).
Truth table
Operand1 | Operand2 | == | != | && | || |
true | true | true | false | true | true |
true | false | false | true | false | true |
false | true | false | true | false | true |
false | false | true | false | false | false |
variable = expression
int x, y, z; x = y = z = 100; // yields value of right-hand expression
Multiplication occurs before addition
total = 2 + 3 * 4; // evaluates to (3 * 4) + 2,
which is 14
total = (2 + 3) * 4; // evaluates to 5 * 4, which is 20
Fortunately, whatever you put in parenthesis has precedence over what is not in parenthesis.
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/expressions.html
The Java programming language allows you to construct compound expressions
and statements from various smaller expressions as long as the data types
required by one part of the expression matches the data types of the other.
Here's an example of a compound expression:
x * y * z
In this particular example, the order in which the expression is evaluated is unimportant because the results of multiplication is independent of order--the outcome is always the same no matter what order you apply the multiplications. However, this is not true of all expressions. For example, the following expression gives different results depending on whether you perform the addition or the division operation first:
x + y / 100 //ambiguous
You can specify exactly how you want an expression to be evaluated by using
balanced parentheses (
and )
. For example to make the
previous expression unambiguous, you could write:
(x + y)/ 100 //unambiguous, recommended
If you don't explicitly indicate the order in which you want the operations in a compound expression to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators with a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator. Thus, the two following statements are equivalent:
x + y / 100 x + (y / 100) //unambiguous, recommended
When writing compound expressions, you should be explicit and indicate with parentheses which operators should be evaluated first. This will make your code easier to read and to maintain.
The following table shows the precedence assigned to the operators. The operators in this table are listed in precedence order: the higher in the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with a relatively lower precedence. Operators on the same line have equal precedence.
postfix operators | [] . (params) expr++ expr-- |
unary operators | ++expr --expr +expr -expr ~
! |
creation or cast | new (type)expr |
multiplicative | * / % |
additive | + - |
shift | << >> >>> |
relational | < > <= >= instanceof |
equality | == != |
bitwise AND | & |
bitwise exclusive OR | ^ |
bitwise inclusive OR | | |
logical AND | && |
logical OR | || |
conditional | ? : |
assignment | = += -= *= /= %= &= ^= |= <<= >>= >>>= |
When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated in left-to-right order. Assignment operators are evaluated right to left.
the two following statements are equivalent:
x + y / 100 x + (y / 100) //unambiguous, recommended
When writing compound expressions, you should be explicit and indicate with parentheses which operators should be evaluated first. This will make your code easier to read and to maintain.
These short cut unary operators increment or decrement a number by one.
Operator | Use | Description |
---|---|---|
++ |
op++ |
Increments op by 1; evaluates to the value of op before
it was incremented |
++ |
++op |
Increments op by 1; evaluates to the value of op after it
was incremented |
-- |
op-- |
Decrements op by 1; evaluates to the value of op before
it was decremented |
-- |
--op |
Decrements op by 1; evaluates to the value of op after it
was decremented |
Note the difference between prefix versus post-fix.
System.out.println(fah + " degrees Fahrenheit is
...");
System.out.println(fah + " degrees Celsius\n");
System.out.println(cel + " degrees Celsius is ...");
System.out.println(cel + " degrees Fahrenheit");
[NOT REQUIRED: EXTRA CREDIT: Write a program that calculates how many of which coins to return as change.
Post a price, allow the user to input the amount of money, and say how much of
which coins come back.]
______________
course
homepage course
calendar