- 论坛徽章:
- 0
|
Using Java operators
An operator takes one or more arguments and produces a new value. Addition(+), subtraction and unary minus(-), multiplication(*), division(/), and assignment(=) all work much the same in any programming language.
All operators produces a value from their operands. In addition, an operator can change the vlaue of an operand. This is called a side effect.
Almost all operators work only with primitives. The exceptions are '=', '==' and '!=', which work with all objects(and are a point of confusion for objects). In addition, the String class supports '+' and '+='.
Precedence
Operator precedence defines how an expression evaluates when several operators are present. The easiest rule to remember is that multiplication and division happen before addintion and subtraction. To make the order of evaluation explicit, you should use parentheses.
Assignment
Assignment is performed with the operator =. It means "take the value of right-hand side and copy it into the left-hand side." An rvalue is any constant, variable or expression that can produce a value, bu an lvalue must be a distinct, named variable.
Assignment of objects is not quite straightforward as assignment of primitives. When you assign primitives you copy the contents from one place to another. When you assign objects, however, things change. You're actually copying a reference from on place to another.
Aliasing during method calls
Aliasing will also occur when you pass an object into a method.
Mathematical operators
The basic mathematical operators are the same as the ones available in most programming languages: addition(+), subtraction(-), division(/), multiplication(*) and modulus(%, which produces the remainder from integer division). Integer division truncates, rather than rounds, the result.
Unary minus and plus operators
Unary minus inverts the sign on the data. Unary plus provides symmetry with unary minus, although it doesn't have any effect.
Auto increment and decrement
Two of the niceer shortcuts are the increment and decrement operators(often refered to as the auto-increment and auto-decrement operators). The decrement operator is -- and means "decrease by one unit." The increment operator is ++ and means "increment by one unit." There are two versions of each type of operator, often called the prefix and postfix versions. For pre-increment and pre-decrement, the operation is performed and the value is produced. For post-increment and post-decrement, the value is produced, then the operation is performed. You can see that for the prefix form you get the value after the operation has been performed, but with the postfix form you get the value before the operation is performed. These are the only operators that have side effects.
Relation operators
Relation operators generate a boolean result. The relational operators are less than(), less than or equal to (=), equivalent(==), and not equivalent(!=). Equivalence and nonequivalence work with built-in data types, but the other comparisions won't work with type boolean.
Testing object equivalence
What if you want to compare the actual contents of an object for equivalence? You must use the special method equals() that exists for all objects. The default behavior of equals() is to compare reference. So unless you override equals() in your new class you won't get the desired behavior.
Logical operators
Each of the logical operators AND(&&), OR(||) and NOT(!) produces a boolean value of true or false based on the logical relationship of its arguments.
Short-circuiting
The expression will be evaluated only until the truth or falsehood of the entire expression can be unambiguously determined. As a result, all the parts of a logical expression might not be evaluated.
Bitwise operators
The bitwise AND operator(&) produces a one in the output bit if both input bits are one; otherwise it produces a zero. The bitwise OR operator(|) produces a one in the output bit if either input bit is a one and produces a zero only if both input bits are zero. The bitwise EXCLUSIVE OR, or XOR(^), produces a one in the output bit if one or the other input bit is a one, but not both. The bitwise NOT(~, also called the ones complement operator)is a unary operator.) Bitwise NOT produces the opposite of the input bit-a one if the input bit is zero, a zero if the input bit is one.
The boolean type is treated as a one-bit value so it is somewhat different. You can perform a bitwise AND, OR and XOR, but you can't perform a bitwise NOT(presumably to prevent confusion with the logical NOT). For booleans the bitwise operators have the same effect as the logical operators except that they do not short circuit. Also, bitwise operations on booleans include an XOR logical operator that is not included under the list of "logical" operators.
Shift operators
The left-shift operator(>) produces the operand to the left of the operator shifted to the right by the number of bits specified after the operator. The signed right shift >> uses sign extension: if the value is positive, zeroes are inserted at the higher-order bits; if the value is negative, ones are inserted at the higher-order bits. Java also added the unsigned right shift >>>, which uses zero extension: regardless of the sign, zeroes are inserted at the higher-order bits.
If you shift a char, byte, or short, it will be promoted to int before the shift takes place, an the result will be an int. Only the five low-order bits of the right-hand side will be used. This prevents you from shifting more than the number of bits in an int. If you're operating on a long, you'll get a long result. Only the six low-order bits of the right-hand side will be used so you can't shift more than the number of bits in a long.
Ternary if-else operator
The expression is of the form:
boolean-exp ? value0 : value1
If boolean-exp evalutes to true, value0 is evaluated and its result becomes the value produced by the operator. If boolean-exp is false, value1 is evaluated and its result becomes the value produced by the operator.
String operaotr +
There's one special usage of an operator in Java: the + operator can be used to concatenate strings.
Common pitfalls when using operators
An extremely common error in C and C++ looks like this:
while (x = y) { // ...... }
In C and C++ the result of this assignment will always be true if y is nonzero, and you'll probably get an infinite loop. In Java, the result of this expression is not a boolean, but the compiler expects a boolean and won't convert from an int, so it will conveniently give you a compile-time error and catch the problem before you ever try to run the program. So the pitfall never happens in Java. The only time you won't get a compile=time error is when x and y are boolean, in which case x = y is a legal expression.
Execution control
In Java, the keywords include if-else, while, do-while, for, and a selection statement called switch.
true and false
All conditional statements use the truth or falsehood of a conditional expression to determine the execution path. Note that Java doesn't allow you to use a number as a boolean, even though it's allowed in C and C++ (where truth is nonzero and falsehood is zero). If you want to use a non-boolean in a boolean test, such as if(a), you must first convert it to a boolean value using a conditional expression, such as if(a!=0).
if-else
Two froms:
if (boolean-expression) statement
or
if (boolean-expression) statement else statement
return
The return keyword has two purposes: it specifies what value a method will return(if it doesn't have a void return value) and it causes that value to be returned immediately.
Iteration
while, do-while and for control looping and are sometimes classified as iteration statements. A statement repeats until the controlling boolean-expression evaluates to false. The form for a while loop is
while (boolean-expression) statement
do-while
The form for do-while is
do statement while (boolean-expression);
The sole difference between while and do-while is that the statement of the do-while always executes at least once, even if the expression evaluates to false the first time. In a while, if the conditional is false the first time the statement never executes.
for
A for loop performs initialization before the first interation. Then it performs conditional testing and, at the end of each iteration, some form of "stepping". The form of the for loop is:
for (initialization; boolean-expression; step) statement
The comma operator
In both the initialization and step portions of the control expression you can have a number of statements separated by commas, and those statements will be evaluated sequentially.
break and continue
Inside the body of the iteration statements you can also control the flow of the loop by using break and continue. break quits the loop without executing the rest of the statements in the loop. continue stops the execution of the current interation and goes back to the beginning of the loop to begin the next iteration.
The only place a label is useful in Java is right before an iteration statement. The sole reason to put a label before an iteration is if you're going to nest another iteration or a switch inside it. That's because the break and continue keywords will normally interrupt only the current loop, but when used with a label they'll interrupt the loops up to where the label exists.
1. A plain continue goes to the top of the innermost loop and continues.
2. A labeled continue goes to the label and re-enters the loop right after the label.
3. A break "drops out of the bottom" of the loop.
4. A labeled break drops out of the bottom of the end of the loop denoted by the label.
switch
The switch is sometimes classified as a selection statement. The switch statement selects from among pieces of code based on the value of an integral expression.
The switch statement is a clean way to implement multi-way selection, but it requires a selector that evaluates to an integral value such as int or char. If you want to use, for example, a string or a floating-point number as a selector, it won't work in a switch statement. For non-integral types, you must use a series of if statements.
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/8554/showart_140758.html |
|