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

Java examples for java.lang:Number

Description

Checks if the given number is positive, 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(isPositive(value));
    }/*  w  w  w.java  2  s  .c  om*/

    /**
     * Checks if the given number is positive, that is > 0. Properly handles the
     * following classes:
     * <ul>
     * <li>Byte</li>
     * <li>Short</li>
     * <li>Integer</li>
     * <li>Long</li>
     * <li>Float</li>
     * <li>Double</li>
     * <li>BigInteger (and derivatives that adhere to the Comparator<BigInteger>
     * interface)</li>
     * <li>BigDecimal(and derivatives that adhere to the Comparator<BigDecimal>
     * interface)</li>
     * <li>AtomicInteger</li>
     * <li>AtomicLong</li>
     * </ul>
     * @param value The value to check
     * @return True is value is not null and its value > 0.
     */
    public static boolean isPositive(Number value) {
        boolean isPositive = false;
        if (value != null) {
            if (BigDecimal.class.isAssignableFrom(value.getClass())) {
                isPositive = (((BigDecimal) value)
                        .compareTo(BigDecimal.ZERO) > 0);
            } else if (BigInteger.class.isAssignableFrom(value.getClass())) {
                isPositive = (((BigInteger) value)
                        .compareTo(BigInteger.ZERO) > 0);
            } else {
                isPositive = (value.doubleValue() > 0);
            }
        }
        return isPositive;
    }

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