Checks if the given number is positive or 0, that is >= 0. - Java java.lang

Java examples for java.lang:Number

Description

Checks if the given number is positive or 0, that is >= 0.

Demo Code


//package com.java2s;
import java.math.BigDecimal;
import java.math.BigInteger;

public class Main {
    public static void main(String[] argv) throws Exception {
        Number value = new Integer(2);
        System.out.println(isPositiveOrZero(value));
    }/*from   w  w  w .  ja v  a 2  s  .com*/

    /**
     * Checks if the given number is positive or 0, that is >= 0.
     * @param value The value to check
     * @return True is value is not null and its value >= 0.
     */
    public static boolean isPositiveOrZero(Number value) {
        boolean isPositiveOrZero = false;
        if (value != null) {
            if (BigDecimal.class.isAssignableFrom(value.getClass())) {
                isPositiveOrZero = (((BigDecimal) value)
                        .compareTo(BigDecimal.ZERO) >= 0);
            } else if (BigInteger.class.isAssignableFrom(value.getClass())) {
                isPositiveOrZero = (((BigInteger) value)
                        .compareTo(BigInteger.ZERO) >= 0);
            } else {
                isPositiveOrZero = (value.doubleValue() >= 0);
            }
        }
        return isPositiveOrZero;
    }

    /**
     * Checks if the Class of the given object is assignable from a reference
     * Class.
     * @param value The object to check.
     * @param clazz The reference Class.
     * @return True if value, it's Class and clazz are not null and value is
     *         assignable from clazz; false otherwise.
     */
    public static boolean isAssignableFrom(Object value, Class clazz) {
        return isAssignableFrom((value != null) ? value.getClass()
                : (Class) null, clazz);
    }

    /**
     * Checks if the given Class is assignable from a reference Class.
     * @param value The Class to check.
     * @param clazz The reference Class.
     * @return True if value and clazz are not null and value is assignable from
     *         clazz; false otherwise.
     */
    @SuppressWarnings("unchecked")
    public static boolean isAssignableFrom(Class value, Class clazz) {
        return (clazz != null) && (value != null)
                && clazz.isAssignableFrom(value); // unchecked
    }
}

Related Tutorials