I have to write a method that has a parameter of type Integer and has to return an object of type Character. If the value of the given parameter is presentable as a Character object, Return it as a Character. Else return null.
My task is poorly formulated it says: "Unsafe conversions (e.g. from int to char) are not allowed in your code" I suppose it is not unsafe but also not allowed somehow?
My Code so far:
public Character methodName (Integer i) {
if (i >= 0 && i <= Character.MAX_VALUE) {
return Character.valueOf((char) i.intValue()); //unsafe conversion
}
else
return null;
}
I tried fixing it by any means but just could not come up with an solution not using the unsafe conversion, thank you very much in advance for helping!
Solution to this weird formulated task:
public Character methodName (Integer i) {
if (i >= 0 && i <= Character.MAX_VALUE) {
return (Character.toChars(i)[0]); //<- solution
}
else
return null;
}
To my mind
if (i >= 0 && i <= Character.MAX_VALUE) {
return Character.valueOf((char) i.intValue());
}
is completely safe according to your teacher's definition of "safe".
SO my teacher said it is indeed unsafe, because the value range of int is 2^32 and of char is 2^16.
The if
test ensures that you only cast i.intValue()
to a char
when i
is in the required (safe) range.
The flipside is that if a provably correct range check is not sufficient to make this "safe" enough for your teacher, then AFAIK there isn't a "safe" solution. All other less direct solutions also entail an explicit or implicit range check in some form ... and will therefore also be "unsafe".