OCP 17 Exam - chapter 2 notes (numeric promotions, operators)
- unary = 1 param, binary = 2 params, ternary = 3 params
- numeric promotions rules:
- always to larger data type, e.g.
short->int - integral type is promoted to floating point if used together,
- e.g.
var z = (double) 1.0 + (short) 1- result isdouble
- e.g.
- smaller types
byte,short,charare promoted tointif used in arithmetic ops (+,*, etc.),- e.g.
short s = 1 + (short)(1 * 2)- doesn’t compile, because1+implicitly casts toint
- e.g.
- always to larger data type, e.g.
float y = 2.1doesn’t compile, becausefis required!*=automatically casts to smaller type,- e.g.
long l = 1; int i = 2; i=i*l- doesn’t compile, butlong l = 1; int i = 2; i*=ldoes.
- e.g.
- assignment also returns value, examples:
long coyote = (wolf = 3)assigns3towolfandcoyoteif(healthy = true), assignstruetohealthyand satisfiesifstatement
- equality operators can be used only for the same type,
- e.g.
true == 3or"3" == 3doesn’t compile
- e.g.
instanceofis also limited to the same type or superclass or interited type- e.g.
Number num = 3; boolean b = num instanceof String;- doesn’t compile, butb = num instanceof java.util.concurrent.atomic.AtomicInteger;does
- e.g.
null instanceof Stringalways returnsfalse- XOR truth table:
1
2
3
4
XOR true ^ true = false
XOR false ^ false = false
XOR true ^ false = true
XOR false ^ true = true
&always evaluates both operands, where&&evaluates right, only when left is true (similar rule applies to|and||)- e.g.
int i = 6; boolean b = (i >= 6) || (++i <= 7)- after executingi=6, because left of||was true, so no need to evaluate right side (unperformed side effect)
- e.g.
Playground code
https://github.com/RG9/rg-playground-ocp17/blob/main/Chapter2.java
Credit: OCP Oracle Certified Professional Java SE 17 Developer Study Guide
This post is licensed under CC BY 4.0 by the author.