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

Java examples for java.lang:Number

Description

Checks if the given Integer is number 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(isNegativeOrZero(value));
    }//  w w  w. j a v  a 2  s. c  om

    /**
     * Checks if the given Integer is number 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 isNegativeOrZero(Number value) {
        boolean isNegativeOrZero = false;
        if (value != null) {
            if (BigDecimal.class.isAssignableFrom(value.getClass())) {
                isNegativeOrZero = (((BigDecimal) value)
                        .compareTo(BigDecimal.ZERO) <= 0);
            } else if (BigInteger.class.isAssignableFrom(value.getClass())) {
                isNegativeOrZero = (((BigInteger) value)
                        .compareTo(BigInteger.ZERO) <= 0);
            } else {
                isNegativeOrZero = (value.doubleValue() <= 0);
            }
        }
        return isNegativeOrZero;
    }

    /**
     * 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