Concept

How does Java handle arithmetic with wrapper classes?

ComputerScienceOne / Operators

"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."

Related Ideas

How does Java handle arithmetic with wrapper classes? | ComputerScienceOne | Bifalgorithm | Bifalgorithm