JetBrains Academy: Boxing and unboxing - Kamil-Jankowski/Learning-JAVA GitHub Wiki

JetBrains Academy: Boxing and unboxing

Safe converting:

Implement a method for converting a Long value to int (primitive type) according to the following rules:

  • if the given value is null the method should return the default value for int;
  • if the given value is greater than Integer.MAX_VALUE the method should return the max value for int;
  • if the given value is lesser than Integer.MIN_VALUE the method should return the min value for int;
  • otherwise, the method should return the same value as the passed argument.
public static int convert(Long val) {
    if(val == null){
        return 0;
    } else if (val > Integer.MAX_VALUE){
        return Integer.MAX_VALUE;
    } else if (val < Integer.MIN_VALUE){
        return Integer.MIN_VALUE;
    } else {
        return (int) val.longValue();
    }
}

Only true or false:

Implement the given method. It takes a value of Boolean type and returns a boolean. If the passed value is null, the result should be false.

public static boolean toPrimitive(Boolean b) {
    return b != null ? b : false;
}

From Double to Integer:

Implement a method for converting a Double value to int.

  • if the given value is NaN, the method should return the default value for Integer;
  • if the given value is Infinity, the method should return Integer.MAX_VALUE;
  • if the given value is -Infinity, the method should return Integer.MIN_VALUE.
public static int convert(Double val) {
    if("NaN".equals(val)){
        return 0;
    } else if ("Infinity".equals(val)){
        return Integer.MAX_VALUE;
    } else if ("-Infinity".equals(val)){
        return Integer.MIN_VALUE;
    } else {
        return val.intValue();
    }
}