Operators and Assignments(1)

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 of these.
1.    Unary operators.
1.1    Increment and Decrement operators ++ --
We have postfix and prefix notation. In post-fix notation value of the variable/expression is modified after the value is taken for the execution of statement. In prefix notation, value of the variable/expression is modified before the value is taken for the execution of statement.

x = 5; y = 0; y = x++;  Result will be x = 6, y = 5
x = 5; y = 0; y = ++x;  Result will be x = 6, y = 6

Implicit narrowing conversion is done, when 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 an integral expression. (1’s complement – 0s to 1s and 1s to 0s)
(~i=-i-1)
Cannot be applied to non-integral types.
1.5    Cast ()
Persuades compiler to allow certain assignments. Extensive checking is done at compile and runtime to ensure type-safety.

2.    Arithmetic operators - *, /, %, +, -
·    Can be applied to all numeric types.
·    Can be applied to only the numeric types, except ‘+’ – it can be applied to Strings as well.
·    All arithmetic operations are done at least with ‘int’. (If types are smaller, promotion happens. Result will be 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 result 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 on wrapper objects(Double or Float) with NaN values compares Nan’s correctly.
·    Infinities are ordinal. X == Double.POSITIVE_INFINITY will give expected result.
·    + also performs String concatenation (when any operand in an expression is a String). The language itself overloads this operator. toString() method of 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 that object is called. (“Vel” + 3 will work.)
·    Be aware of 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 from the 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 of bits shifted. Also called arithmetic right shift.
·    >>> performs an unsigned logical right shift. 0 bits are brought in from the left. This operator exists since Java doesn’t provide an unsigned data type (except char). >>> changes the sign of a negative number to be positive. So don’t use it with negative numbers, if you want to preserve the sign. Also don’t use it with types smaller than int. (Since types smaller than int are promoted to an int before any shift operation and the result is cast down again, so the end result is unpredictable.)
·    Shift operators can be applied to only integral types.
·    -1 >> 1 is –1, not 0.
·    1 << 31 will become the minimum value that 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 more than the number of bits the type of result can have. ( i.e. int 32, long 64) RHS operand is reduced to RHS % x where x is no of bits in type of result.  
int x;
x == x >> 32 // ture
x =  x >> 33;  // Here actually what happens is x >> 1
·    if right side is negative, for int, use low 5 bits; for long, use 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 an object at runtime. Checking is done at compile and runtime same as the cast operator.
·    Returns true if the object denoted by LHS reference can be cast to RHS type.
·    LHS should be an object reference expression, variable or an array reference.
·    RHS should be a class (abstract classes are fine), an interface or an array type, 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 an array reference and of type RHS.
·    x instanceof Component[] – legal.
·    x instanceof [] – illegal. Can’t test for ‘any array of any type’
·    Returns false if LHS is null, no exceptions are thrown.
·    If x instanceof Y is not allowed by compiler, then Y y = (Y) x is 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 make much sense. Use equals method for meaningful comparisons. (Make sure that the class implements equals in a meaningful way, like for X.equals(Y) to be true, Y instance of X must be true as well)
·    For String literals, == will return true, this is because of compiler optimization.
5.    Bit-wise operators - &, ^, |
·    Operate on numeric and boolean operands.
·    & - AND operator, both bits must be 1 to produce 1.
·    | - OR operator, any one bit can be 1 to produce 1.
·    ^ - XOR operator, any one bit can be 1, but not both, to produce 1.
·    In case of booleans true is 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 not be evaluated (hence the name short-circuit), if the result can be determined only by looking at LHS.
·    false && X  is always false.
·    true || X is always true.
·    RHS is evaluated only if the result 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 will be assigned to a if x is 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 first, and the value of the assignment (0) assigned to b, then the value of that assignment (again 0) is assigned to a.
·    Extended assignment operators do an 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 an int
b += 10; // OK, += does an 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 that operands are evaluated from left to right, and the operations are executed in the order of precedence 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) ++ --    Left to 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    &    Left to 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 to Left

时间: 2016-02-08

Operators and Assignments(1)的相关文章

Operators and Assignments(2)

Objective 2) Determine the result of applying the boolean equals(Object) method to objects of any combination of the classes java.lang.String java.lang.Boolean and java.lang.Object. The equals method can be considered to perform a deep comparison of

operators:php operators

php operatorsthis section lists the different operators used in php.arithmetic operators + addition x=2x+2 4 - subtraction x=25-x 3 * multiplication x=4x*5 20 / division 15/55/2 32.5 % modulus (division remainder) 5%210%810%2 120 ++ increment x=5x++

win8-access control assistance operators

问题描述 access control assistance operators 在win8.1 的 计算机管理 本地用户和组中,今天 突然发现 access control assistance operators 这个组, 想删除掉它 提示 无法删除 无法使用内置用户 删除 删除掉 对于 使用系统有没有太大影响? 如何才能删掉它? 解决方案 http://zhidao.baidu.com/link?url=nN7KQRTeMc3_VnRtaT8KW9RIHLRxGRlxbVm7IaY2NfG

Effective C++ 读书笔记之Part2.Constructors, Destructors, and Assignment Operators

5.Know what functions C++ silently writes and calls. 总结:编译器可以暗自为class创建default构造函数.copy构造函数.copy assginment操作符,以及析构函数.这些函数都是public的,并且是inline的. 6.Explicitly disallow the use of compiler-generated functions you to not want. 总结:为驳回编译器自动(暗自)提供的机能,可将相应的成

Es6系列之destructuring assignments

Ecmascript 6简称es6,是javascript下一代标准,还处在开发阶段,估计2014年底发布,有关更多浏览器对es6的支持情况,点击这里 今天说说es6里对赋值语句的改进,简称解构赋值. 解构赋值 所谓解构赋值其实就是按照模式匹配进行批量赋值 下面的是以往的赋值语句 var a = 1; var b = 2; var c = 3; 以往的方式对于赋值多个变量的时候代码比较多而且不方便,那么es6里对它是怎么改进的呢? 通过以对象或者数组结构组装数据进行赋值,要保证赋值左右值类型相同

Basic Operators Of Swift 2.1

原文出自:标哥的技术博客 前言 运算符是检查.改变或合并值的特殊符号或短语.例如:加号+将两个数相加.更复杂的运算例子包括逻辑与运算符&&或让i值加1的便捷自增运算符++i等. Swift支持大部分标准C语言的运算符,且改进许多特性来减少常规编码错误.例如:赋值符不返回值,以防止把想要判断相等运算符的地方写成赋值符导致的错误.算术运算符(+,-,*,/,%等)会检测并不允许值溢出,以此来避免保存变量时由于变量大于或小于其类型所能承载的范围时导致异常.当然允许你使用Swift的溢出运算符来实

Swift学习之九:基本运行符(Basic Operators)

基本运行符: +(加法.正数) - (减法.负数) *  (乘法) / (除法) % (求余)  : 在Swift中,求余可以是浮点数求余. &&(逻辑与)  || (逻辑或) ^ (逻辑异或)  表示范围的符号:..和...(两个点:不包括下界和三个点包括下界) ++, -- 赋值操作符 // 赋值操作符=,表示把某个值赋给对应的常量或者变量 let b = 10 var a = 5 如果右边的赋值是一个元组,那么可以分解成多个常量或者变量: // x = 1, y = 2 let (x

PostgreSQL 统计信息pg_statistic格式及导入导出dump_stat - 兼容Oracle

标签 PostgreSQL , dump_stat , 统计信息 , 导出导入 背景 <PostgreSQL 规格评估 - 微观.宏观.精准 多视角估算数据库性能(选型.做预算不求人)> EXPLAIN是PG数据库用于输出SQL执行计划的语法, 1.生成的执行计划中包含COST一项. 如果校准了成本因子,COST可以和SQL实际执行时间对其.因子校对的方法如下,实际上每一种硬件,我们只需要校对一遍即可. <优化器成本因子校对(disk,ssd,memory IO开销精算) - Postg

TYAN_S8230做硬Raid

一:建立RAID0. 开机后当出现以下画面时,按Ctrl+F进入RAID设定页面.     RAID设定页面:       意思大意如下: 按数字键 1 View Drive Assignments -查看磁盘情况 按数字键 2 LD View / LD Define Menu -建立磁盘阵列菜单 按数字键 3 Delete LD Menu -删除磁盘阵列 按数字键 4 Controller Configuration -查看磁盘阵列RAID状况   按2进入建立RAID:    同时按下Ctr