Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a nullable integer value in Java (Short, Long etc.)

Tags:

java

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.

like image 503
yktoo Avatar asked Sep 17 '26 03:09

yktoo


1 Answers

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;
like image 196
Dreamspace President Avatar answered Sep 19 '26 16:09

Dreamspace President