5) Operators and Assignments
Objective 1)
Determine the result of applying any operator including assignment operators and instanceof to operands of any type class Scope or accessibility or any combination.
1. Unary operators.
1.1 Increment and decrement operators + +-
We have postfix and prefix notation. In Post-fix notation value of the variable/expression was modified after the ' value is ' taken for the execution of statement. In prefix notation, value of the variable/expression was modified before the value is taken for the execution of statement .
x = 5; y = 0; y = x + +; result would be x = 6, y = 5
x = 5; y = 0; y = ++x; result would be x = 6, y = 6
Implicit narrowing conversion is done while applied to byte, short or char.
1.2 unary minus and unary plus +-
+ has no effect than to stress positivity.
-Negates an expression ' s value. (2 ' s complement for integral expressions)
1.3 Negation!
Inverts the value of a Boolean expression.
1.4 Complement ~
Inverts the bit pattern of a integral expression. (1 ' s complement–0s to 1s and 1s to 0s)
(~i=-i-1)
Cannot is applied to non-integral types.
1.5 Cast ()
Persuades compiler to allow certain assignments. Extensive checking is done in compile and runtime to ensure type-safety.
2. Arithmetic Operators-*,/,%, +,-
· Can is applied to all numeric types.
· Can be applied to only the numeric types, except ' + ' –it can is applied to Strings as.
· All arithmetic operations are is done in least with ' int '. (If types are smaller, promotion happens.) Result would be is of a type at least as wide as the wide type of operands)
· Accuracy is lost silently when arithmetic overflow/error occurs. Result is a nonsense value.
· Integer division or% by zero throws ArithmeticException.
· Floating point arithmetic always loses precision. The following code fragment returns FALSE.
float F = 1.0 f/3.0 F;
if (A * 3.0 F = = 1.0 f) return true;
else return false;
· %-sign of the entirely determined by sign of LHS
· Floating point calculations can produce NaN (square root of a negative no. or% by zero) or infinity/-infinity (division by zero). Float and Double wrapper classes have named constants for NaN and Infinities.
· NaN ' s are non-ordinal for comparisons. X = = Float.nan won ' t work. Use Float.isnan (x) and Double.isnan (x). But equals method in wrapper objects (Double or Float) with Nan values compares Nan ' correctly.
· Infinities are ordinal. X = = Double.positive_infinity would give expected result.
· + also performs string concatenation (when any operand in a expression is a string). The language itself overloads this operator. ToString () method of the Non-string object operands are called to perform concatenation. In case of primitives, a wrapper object is created with the primitive value and toString method of this object is called. ("Vel" + 3 would work.)
· Be aware of the associativity when multiple operands are involved.
SYSTEM.OUT.PRINTLN (1 + 2 + "3"); Prints 33
System.out.println ("1" + 2 + 3); Prints 123
3. Shift operators-<<, >>, >>>
· << performs a signed left shift. 0 bits are brought in and right. Sign bit (MSB) is preserved. (?) Value becomes old value * 2 ^ x where x is no of bits shifted.
· >> performs a signed right shift. Sign bit is brought in from the left. (0 if positive, 1 if negative.) Value becomes old value/2 ^ x where x is no bits shifted. Also called arithmetic right shift.
· >>> performs an unsigned logical right shift. 0 bits are brought in ' left '. This operator exists since Java doesn ' t provide a unsigned data type (except char). >>> changes the sign of a negative number to be positive. So don ' t use it with negative numbers, if your want to preserve the sign. Also don ' t use it with types smaller than int. (Since types smaller than int are promoted to a int before any shift opera The tion and the result are cast down again, so the ' end ' is unpredictable.
· Shift operators can applied to only integral types.
· -1 >> 1 is–1, not 0.
· 1 << would become the minimum value, an int can represent.
· Negative numbers are represented in two ' s complement notation. (Take one ' s complement and add 1 to get two ' s complement)
· Shift operators never shift than the number of bits the type of result can have. (i.e. int, long 64) RHS operand is reduced to RHS% x where x is no of bits in type of.
int x;
x = = x >>//Ture
x = x >> 33; Here actually what happens is x >> 1
· If right side are negative, for int, with low 5 bits; For long, with low 6 bits.
4. Comparison Operators–all return Boolean type.
4.1 Ordinal Comparisons-<=, >, >=
· Only operate on numeric types. Test the relative value of the numeric operands.
· Arithmetic promotions apply. Char can be compared to float.
4.2 Object Type Comparison–instanceof
· Tests the class of object at runtime. Checking is do at compile and runtime same as the cast operator.
· Returns true if the object denoted by LHS reference can is cast to RHS type.
· LHS should be a object reference expression, variable or an array reference.
· RHS should is a class (abstract classes are fine), an interface or a array type, and castable to LHS object reference. Compiler error if LHS & RHS are unrelated.
· Can ' t use Java.lang.Class or its String name as RHS. (?)
· Returns true if LHS is a class or subclass of RHS class
· Returns true if LHS implements RHS interface.
· Returns true if LHS is a array reference and of type RHS.
· x instanceof Component[]–legal.
· x instanceof []–illegal. Can ' t test for ' an ' any array of any type '
· Returns False if LHS is NULL, no exceptions are thrown.
· If x instanceof y allowed by compiler, then y y = (y) x are not a valid cast expression. If x instanceof Y is allowed and returns false, the above-cast is valid but-throws a classcastexception at runtime. If x instanceof Y Returns True, the above cast is valid and runs fine.
4.3 equality comparisons-= =,!=
· For primitives it ' s a straightforward value comparison. (Promotions apply)
· For object references, this doesn ' t is much sense. Use equals to meaningful comparisons. (Make sure this class implements equals in a meaningful way, like for X.equals (y) to is true, Y instance of X must be True as OK)
· For String literals, = = would return True and this is because of compiler optimization.
5. Bit-wise operators-^, ^, |
· Operate on numeric and Boolean operands.
· &-operator, both bits must is 1 to produce 1.
· | -or operator, any one bit can is 1 to produce 1.
· ^-XOR operator, any one bit can is 1, but not both, to produce 1.
· In the case of Booleans true be 1, false is 0.
· Order:and, XOR, OR.
· Can ' t cast any other type to Boolean.
6. Short-circuit logical operators-&&, | |
· Operate only on Boolean types.
· RHS might is evaluated (hence the name short-circuit), if the can is determined only by looking at LHS.
· False && X is always false.
· true | | X is always true.
· The RHS is evaluated only if the ' is ' is ' not ' certain from the LHS.
7. Ternary operator
· Format a = x? B:C;
· X should be a Boolean expression.
· Based on X, either B or C is evaluated. Both are never evaluated.
· b'll be assigned to a if x are true, else C is assigned to a.
· B and C should be assignment compatible to a.
· B and C are made identical during the operation according to promotions.
8. Assignment operators.
· Simple assignment =.
· op= Calculate and assign operators (extended, assignment operators)
· *=, /=, %=, +=, -=
· x = = y means x = x + y. But x is evaluated only once. Be aware.
· Assignment of reference variables copies the reference value, not the object body.
· Assignment has value, value of LHS after assignment. So a = b = c = 0 is legal. c = 0 is executed-assignment (0) assigned to B, then the value of that assignment (again 0) is Assigned to a.
· Extended assignment operators do a implicit cast. (useful when applied to byte, short or char)
byte B = 10;
B = B + 10; Won ' t compile, explicit cast reqd since the expression evaluates to a int
B + 10; OK, + + does a implicit cast from int to byte
9. General
· In Java, No overflow or underflow of integers happens. i.e. the values wrap around. Adding 1 to the maximum int value results in the minimum value.
· Always Keep in mind this operands are evaluated from left to right, and the operations are the order of executed ence and associativity.
· Unary Postfix operators and all binary operators (except assignment operators) have left to right assoiciativity.
· All unary operators (except postfix operators), assignment operators, ternary operator, object creation and cast operators Have right to left assoiciativity.
· Inspect the following code.
public class Precedence {
Final public static void main (String args[]) {
int i = 0;
i = i++;
i = i++;
i = i++;
System.out.println (i); Prints 0, since = operator has the lowest precedence.
int array[] = new INT[5];
int index = 0;
Array[index] = index = 3; 1st element Get assigned to 3, not the 4th element
for (int c = 0; c < array.length C + +)
System.out.println (Array[c]);
System.out.println ("index is" + index); Prints 3
}
}
Type of Operators Operators associativity
Postfix operators []. (parameters) + +-Right
Prefix unary operators + +--~! Right to Left
Object creation and cast new (type) right to left
Multiplication/division/modulus */% left to right
Addition/subtraction +-Left to right
Shift >> >>> << left to right
Relational < <= > >= instanceof left to right
Equality = =!= left to right
Bit-wise/boolean and & Right
Bit-wise/boolean XOR ^ left to right
Bit-wise/boolean OR | Left to right
Logical and (short-circuit or Conditional) && left to right
Logical or (short-circuit or Conditional) | | Left to right
Ternary? : Right to Left
Assignment = + = *=/=%= <<= >>= >>>= &= ^= |= Right
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.