Bifalgorithm post · Computer science one · Operators
How does Java handle arithmetic with wrapper classes?
How does Java handle arithmetic with wrapper classes? (Computer science one · Operators) — "In addition, you can mix the wrapper classes with their primitive t…
Ideas in this flowchart
- Primitive types and wrapper classes can be mixed in arithmetic expressions.
- Compatible primitive and wrapper values are automatically combined for arithmetic.
- An int and an Integer can be mixed: c = a + b.
- A double and a Double can be mixed: z = x + y.
- Values of all these types can be mixed: double u = a + x + b + y.
- This behavior uses autoboxing and, in arithmetic expressions, autounboxing.
- A wrapper object stores the value of a primitive type and is unboxed when arithmetic requires a primitive.
- The compiler performs the conversion automatically and transparently.
- Wrapper classes are object references, so they can contain null.
- Using a null wrapper reference in arithmetic causes a NullPointerException.
- The exception can be caught and handled; otherwise, it becomes a fatal error.
- For c = a + d, the compiler effectively uses c = a + d.doubleValue().
- Calling doubleValue() on a null reference is impossible, so the NullPointerException is thrown.