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.
Feed/

How does Java handle arithmetic with wrapper classes?

No cover

Channel

Computer science one

1 page

"In addition, you can mix the wrapper classes with their primitive types. You must be careful though. The wrapper classes are object references which can be null. If a null reference is used in an arithmetic expression, it will result in a NullPointerException which can be caught and handled. If not caught, it will end up being a fatal error.\n\nint a = 10, c;\n\nInteger b = 20;\n\n// int and Integer can be mixed:\n\nc = a + b;\n\ndouble x = 3.14, z;\n\nDouble y = 2.71;\n\n// double and Double can be mixed:\n\nz = x + y;\n\n// all types can be mixed:\n\ndouble u = a + x + b + y;\n\n// Be careful:\n\nInteger d = null;\n\nc = a + d; // NullPointerException\n\nThis works because of a mechanism called autoboxing, or autounboxing in this case. The wrapper class is acting like a “box”: it is an object that stores the value of a primitive type. When it gets used in an arithmetic expression, it gets “unboxed” and converted to a primitive type so that the arithmetic operation is performed on compatible primitive types. This is all done by the compiler and is completely transparent to us.\n\nHowever, that is the reason that we may get a NullPointerException. Our code actually gets converted from c = a + d; to c = a + d.doubleValue();. The doubleValue() method returns a double primitive value. However, if d is null, you can’t call a method on it; thus the NullPointerException is thrown as a consequence."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.