Is there any standard way of converting between non-primitive integer types in Java that properly retains null values? Something like:
// Pseudocode
Short shortVal = null;
Long longVal = Numbers.toLong(shortVal); // longVal is expected to be null here
Obviously I cannot use shortVal.longValue() here as a NullPointerException will be thrown.
Plain simple "casting" and the "ternary conditional operator" would be the minimal and fastest solution.
Short shortVal = null;
Long longVal = shortVal == null ? null : (long) shortVal;
Since you don't seem to know about casting, here's an example that does not work - and how to fix it. Mind that the problem of null is completely ignored here - this is just a quirky aspect of casting that you might want to know, that's all.
Double doubleVal = 1d;
Float floatVal = (float) doubleVal; // Inconvertible types!
Working version:
Double doubleVal = 1d;
Float floatVal = (float) (double) doubleVal;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With