Expressions: Slides Are Adapted From The Originals Available at
Expressions: Slides Are Adapted From The Originals Available at
Java
CHAPTER 3
ERIC S. ROBERTS
Expressions
Whats twice eleven? I said to Pooh. (Twice what? said Pooh to Me.) I think that it ought to be twenty-two. Just what I think myself, said Pooh. A. A. Milne, Now We Are Six, 1927
Chapter 3Expressions
Expressions in Java
The heart of the Add2Integers program from Chapter 2 is the line
int total = n1 + n2;
The n1 + n2 that appears to the right of the equal sign is an example of an expression, which specifies the operations involved in the computation.
An expression in Java consists of terms joined together by operators. Each term must be one of the following:
A constant (such as 3.14159265 or "hello, world") A variable name (such as n1, n2, or total) A method calls that returns a values (such as readInt) An expression enclosed in parentheses
This type is used to represent integers, which are whole numbers such as 17 or 53.
double
This type is used to represent numbers that include a decimal fraction, such as 3.14159265. In Java, such values are called floating-point numbers; the name double comes from the fact that the representation uses twice the minimum precision.
The arithmetic operators: * multiply + add / divide - subtract 16-bit integers in the range 32768 to 32767 % remainder 32-bit integers in the range The relational operators: != not equal 2146483648 to 2146483647 = = equal to <= less or equal < less than 64-bit integers in the range 9223372036754775808 to 9223372036754775807 > greater than >= greater or equal 32-bit floating-point numbers in the range The arithmetic operators except % 1.4 x 10-45 to 3.4028235 x 10-38 The relational operators 64-bit floating-point numbers in the range 4.39 x 10-322 to 1.7976931348623157 x 10308 8-bit integers in the range 128 to 127 16-bit characters encoded using Unicode the values true and false The relational operators The logical operators: && and || or
! not
boolean
by a minus sign, as in 0, total 42, -1, or 1000000. Floating-point constants include a decimal point, as in 3.14159265 (contains an int) or 42 10.0. Floating-point constants can also be expressed in scientific notation by adding the letter E and an exponent after the digits of the Each variable has the following attributes: number, so that 5.646E-8 represents the number 5.646 x 10-8. A name, which enables you to differentiate one variable from another. The two constants of type boolean are true and false. A type, which specifies what type of value the variable can contain. Character and string constants are discussed in detail in Chapter 8. A value , which represents the current the variable. For the moment, all you need to knowcontents is that aof string constant consists of a sequence of characters enclosed infixed. double The quotation marks, such The name and type of a variable are value changes as "hello, world".
Variable Declarations
In Java, you must declare a variable before you can use it. The declaration establishes the name and type of the variable and, in most cases, specifies the initial value as well. The most common form of a variable declaration is
type name = value;
where type is the name of a Java primitive type or class, name is an identifier that indicates the name of the variable, and value is an expression specifying the initial value. Most declarations appear as statements in the body of a method definition. Variables declared in this way are called local variables and are accessible only inside that method.
Variables may also be declared as part of a class. These are called instance variables and are covered in Chapter 6.
Java Identifiers
Names for variables (and other things) are called identifiers. Identifiers in Java conform to the following rules:
A variable name must begin with a letter or the underscore character. The remaining characters must be letters, digits, or underscores. The name must not be one of Javas reserved words:
abstract boolean break byte case catch char class const continue default do double else extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while
Identifiers should make their purpose obvious to the reader. Identifiers should adhere to standard conventions. Variable names, for example, should begin with a lowercase letter.
Use of Variables
GRect r1 = new GRect(10, 10, 50, 30); GRect r2 = new GRect(20, 20, 50, 30); GRect r3 = new GRect(30, 30, 50, 30); GRect r4 = new GRect(40, 40, 50, 30); add(r1); add(r2); add(r3); add(r4);
Use of Variables
int h = 30; GRect r1 = new GRect(10, 10, 50, h); GRect r2 = new GRect(20, 20, 50, h); GRect r3 = new GRect(30, 30, 50, h); GRect r4 = new GRect(40, 40, 50, h); add(r1); add(r2); add(r3); add(r4);
Use of Variables
int h = 50; GRect r1 = new GRect(10, 10, 50, h); GRect r2 = new GRect(20, 20, 50, h); GRect r3 = new GRect(30, 30, 50, h); GRect r4 = new GRect(40, 40, 50, h); add(r1); add(r2); add(r3); add(r4);
Use of Variables
int x = 10; int h = 50; GRect r1 = new GRect(x, 10, 50, h); GRect r2 = new GRect(x+10, 20, 50, h); GRect r3 = new GRect(x+20, 30, 50, h); GRect r4 = new GRect(x+30, 40, 50, h); add(r1); add(r2); add(r3); add(r4);
Assignment Statements
You can change the value of a variable in your program by using an assignment statement, which has the general form:
variable = expression;
The effect of an assignment statement is to compute the value of the expression on the right side of the equal sign and assign that value to the variable that appears on the left. Thus, the assignment statement
total = total + value;
adds together the current values of the variables total and value and then stores that sum back in the variable total. When you assign a new value to a variable, the old value of that variable is lost.
Use of Variables
int x = 10; int h = 50; GRect r1 = new GRect(x, 10, 50, h); x = x + 10; GRect r2 = new GRect(x, 20, 50, h); x = x + 10; GRect r3 = new GRect(x, 30, 50, h); x = x + 10; GRect r4 = new GRect(x, 40, 50, h); add(r1); add(r2); add(r3); add(r4);
Shorthand Assignments
Statements such as
total = total + value;
where op is any of Javas binary operators. The effect of this statement is the same as
variable = variable op (expression);
Use of Variables
int x = 10; int h = 50; GRect r1 = new GRect(x, 10, 50, h); x += 10; GRect r2 = new GRect(x, 20, 50, h); x += 10; GRect r3 = new GRect(x, 30, 50, h); x += 10; GRect r4 = new GRect(x, 40, 50, h); add(r1); add(r2); add(r3); add(r4);
}
}
Output:
The effect of this statement is to add one to the value of x, which means that this statement is equivalent to
x += 1;
The -- operator (which is called the decrement operator) is similar but subtracts one instead of adding one.
The ++ and -- operators are more complicated than shown here, but it makes sense to defer the details until Chapter 11.
seems as if it should have the value 2.8, but because both operands are of type int, Java computes an integer result by throwing away the fractional part. The result is therefore 2. If you want to obtain the mathematically correct result, you need to convert at least one operand to a double, as in
(double) 14 / 5
The conversion is accomplished by means of a type cast, which consists of a type name in parentheses.
1.8
9.0 (double) 9 / 5 * c + 32
The result of the % operator make intuitive sense only if both operands are positive. The examples in this book do not depend on knowing how % works with negative numbers. The remainder operator turns out to be useful in a surprising number of programming applications and is well worth a bit of study.
Precedence
If an expression contains more than one operator, Java uses precedence rules to determine the order of evaluation. The arithmetic operators have the following relative precedence:
unary highest
(type cast) / %
lowest
Thus, Java evaluates unary - operators and type casts first, then the operators *, /, and %, and then the operators + and -.
Precedence applies only when two operands compete for the same operator. If the operators are independent, Java evaluates expressions from left to right. Parentheses may be used to change the order of operations.
32
32
0
3 30
4
8
( 1 + 2 ) % 3 * 4 + 5 * 6 / 7 * ( 8 % 9 ) + 10
Exercise: Precedence
What would the value of total be?
unary -
(type cast) / % -
highest
* +
lowest
Boolean Expressions
In many ways, the most important primitive type in Java is boolean, even though it is by far the simplest. The only values in the boolean domain are true and false, but these are exactly the values you need if you want your program to make decisions.
The name boolean comes from the English mathematician George Boole who in 1854 wrote a book entitled An Investigation into the Laws of Thought, on Which are Founded the Mathematical Theories of Logic and Probabilities. That book introduced a system of logic that has come to be known as Boolean algebra, which is the foundation for the boolean data type.
George Boole (1791-1871)
Boolean Operators
The operators used with the boolean data type fall into two categories: relational operators and logical operators. There are six relational operators that compare values of other types and produce a boolean result: = = Equals != Not equals < Less than <= Less than or equal to >= Greater than or equal to > Greater than For example, the expression n <= 10 has the value true if x is less than or equal to 10 and the value false otherwise.
Assume x is 3, y is 5.
Expression x > 0 x < 3 x > 3 x >= 3 x <= 3 x <= y x == y x != y Value true false false true true true false true
Assume x is 3, y is 5.
Can use arithmetic operations. Expression
x (x % ((x+1) x + y > 0 2) == 0 % 2) == 0 y >= 8
Value
false false true true
Boolean Operators
There are also three logical operators:
&& Logical AND
|| Logical OR ! Logical NOT p && q means both p and q p || q means either p or q (or both) !p means the opposite of p
Boolean Operators
true && true
false && true true && false false && false true || true false || true true || false false || false ! true ! false
true
false false false true true true false false true
Assume x is 3, y is 5.
Expression x > 0 && x < 5 x < 3 || x > 3 x < 3 || x >= 3 !(x > y) !(y x > 0) Value true false true true false
Boolean Expressions
public class BooleanExpressions extends ConsoleProgram { public void run() { int x = 3; int y = 5; boolean b = x - y > 0; println("x - y > 0 is " + b); b = ((x + 1) % 2) == 0; println("((x+1) % 2) == 0 is " + b); b = x > 0 && x < 5; println("x > 0 && x < 5 is " + b); b = x < 3 || x > 3; println("x < 3 || x > 3 is " + b); b = !(x > y); println("!(x > y) is " + b); b = !(y - x > 0); println("!(y x > 0) is " + b); b = y % 2 != 0; println("y % 2 != 0 is " + b); } }
The || operator means either or both, which is not always clear in the English interpretation of or. Be careful when you combine the ! operator with && and || because the interpretation often differs from informal English.
Short-Circuit Evaluation
Java evaluates the && and || operators using a strategy called short-circuit mode in which it evaluates the right operand only if it needs to do so. For example, if n is 0, the right hand operand of && in
n != 0 && x % n == 0
is always false, the rest of the expression no longer matters. One of the advantages of short-circuit evaluation is that you can use && and || to prevent execution errors. If n were 0 in the earlier example, evaluating x % n would cause a division by zero error.
Short-Circuit Evaluation
public class ShortCircuit extends ConsoleProgram { public void run() { int x = 10; int y = 0; boolean b1 = (y!= 0) && x/y > 1; println("Boolean value is " + b1); boolean b2 = false && x/y == 4; println("Boolean value is " + b2); boolean b3 = true || x/y == 4; println("Boolean value is " + b3); boolean b4 = x/y > 1; // Raises a div. by zero exception. println("Boolean value is " + b4); } }