Saturday, February 17, 2018

Java Operator Precedence, ++i vs i++


https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/QandE/answers_operators.html
https://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i

Operator Precedence
OperatorsPrecedence
postfixexpr++ expr--
unary++expr --expr +expr -expr ~ !
multiplicative* / %
additive+ -
shift<< >> >>>
relational< > <= >= instanceof
equality== !=
bitwise AND&
bitwise exclusive OR^
bitwise inclusive OR|
logical AND&&
logical OR||
ternary? :
assignment= += -= *= /= %= &= ^= |= <<= >>= >>>=


  • ++i will increment the value of i, and then return the incremented value.
     i = 1;
     j = ++i;
     (i is 2, j is 2)
  • i++ will increment the value of i, but return the original value that i held before being incremented.
     i = 1;
     j = i++;
     (i is 2, j is 1)
  1. Consider the following code snippet:
    arrayOfInts[j] > arrayOfInts[j+1]
    
    Question: What operators does the code contain?
    Answer: >+
  2. Consider the following code snippet:
    int i = 10;
    int n = i++%5;
    
    1. Question: What are the values of i and n after the code is executed?
      Answer: i is 11, and n is 0.
    2. Question: What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))?
      Answer: i is 11, and n is 1.
  3. Question: To invert the value of a boolean, which operator would you use?
    Answer: The logical complement operator "!".
  4. Question: Which operator is used to compare two values, = or == ?
    Answer: The == operator is used for comparison, and = is used for assignment.
  5. Question: Explain the following code sample: result = someCondition ? value1 : value2;
    Answer: This code should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."

No comments:

Post a Comment

java special for collection size, array size, and string size

Size: For Collections (eg: Map, List, etc ): usually it use collection.size(), eg         Map<Character, Integer> map ...