Java/Data Type/Primitive Data Type

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A mutable boolean wrapper.

   
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.Serializable;

/**
 * A mutable <code>boolean</code> wrapper.
 * 
 * @see Boolean
 * @since 2.2
 * @author Apache Software Foundation
 * @version $Id: MutableBoolean.java 491052 2006-12-29 17:16:37Z scolebourne $
 */
public class MutableBoolean implements Mutable, Serializable, Comparable {
    /**
     * Required for serialization support.
     * 
     * @see java.io.Serializable
     */
    private static final long serialVersionUID = -4830728138360036487L;
    /** The mutable value. */
    private boolean value;
    /**
     * Constructs a new MutableBoolean with the default value of false.
     */
    public MutableBoolean() {
        super();
    }
    /**
     * Constructs a new MutableBoolean with the specified value.
     * 
     * @param value
     *            a value.
     */
    public MutableBoolean(boolean value) {
        super();
        this.value = value;
    }
    /**
     * Constructs a new MutableBoolean with the specified value.
     * 
     * @param value
     *            a value.
     * @throws NullPointerException
     *             if the object is null
     */
    public MutableBoolean(Boolean value) {
        super();
        this.value = value.booleanValue();
    }
    // -----------------------------------------------------------------------
    /**
     * Returns the value of this MutableBoolean as a boolean.
     * 
     * @return the boolean value represented by this object.
     */
    public boolean booleanValue() {
        return value;
    }
    /**
     * Compares this mutable to another in ascending order.
     * 
     * @param obj
     *            the mutable to compare to
     * @return zero if this object represents the same boolean value as the argument; a positive value if this object
     *         represents true and the argument represents false; and a negative value if this object represents false
     *         and the argument represents true
     * @throws ClassCastException
     *             if the argument is not a MutableInt
     */
    public int compareTo(Object obj) {
        MutableBoolean other = (MutableBoolean) obj;
        boolean anotherVal = other.value;
        return value == anotherVal ? 0 : (value ? 1 : -1);
    }
    // -----------------------------------------------------------------------
    /**
     * Compares this object to the specified object. The result is <code>true</code> if and only if the argument is
     * not <code>null</code> and is an <code>MutableBoolean</code> object that contains the same
     * <code>boolean</code> value as this object.
     * 
     * @param obj
     *            the object to compare with.
     * @return <code>true</code> if the objects are the same; <code>false</code> otherwise.
     */
    public boolean equals(Object obj) {
        if (obj instanceof MutableBoolean) {
            return value == ((MutableBoolean) obj).booleanValue();
        }
        return false;
    }
    // -----------------------------------------------------------------------
    /**
     * Gets the value as a Boolean instance.
     * 
     * @return the value as a Boolean
     */
    public Object getValue() {
        return this.value;
    }
    /**
     * Returns a suitable hashcode for this mutable.
     * 
     * @return the integer <code>1231</code> if this object represents <code>true</code>; returns the integer
     *         <code>1237</code> if this object represents <code>false</code>.
     */
    public int hashCode() {
        return value ? Boolean.TRUE.hashCode() : Boolean.FALSE.hashCode();
    }
    /**
     * Sets the value.
     * 
     * @param value
     *            the value to set
     */
    public void setValue(boolean value) {
        this.value = value;
    }
    /**
     * Sets the value from any Boolean instance.
     * 
     * @param value
     *            the value to set
     * @throws NullPointerException
     *             if the object is null
     * @throws ClassCastException
     *             if the type is not a {@link Boolean}
     */
    public void setValue(Object value) {
        setValue(((Boolean) value).booleanValue());
    }
    /**
     * Returns the String value of this mutable.
     * 
     * @return the mutable value as a string
     */
    public String toString() {
        return String.valueOf(value);
    }
}
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Provides mutable access to a value.
 * <p>
 * <code>Mutable</code> is used as a generic interface to the implementations in this package.
 * <p>
 * A typical use case would be to enable a primitive or string to be passed to a method and allow that method to
 * effectively change the value of the primitive/string. Another use case is to store a frequently changing primitive in
 * a collection (for example a total in a map) without needing to create new Integer/Long wrapper objects.
 * 
 * @author Matthew Hawthorne
 * @since 2.1
 * @version $Id: Mutable.java 618693 2008-02-05 16:33:29Z sebb $
 */
interface Mutable {
    /**
     * Gets the value of this mutable.
     * 
     * @return the stored value
     */
    Object getValue();
    /**
     * Sets the value of this mutable.
     * 
     * @param value
     *            the value to store
     * @throws NullPointerException
     *             if the object is null and null is invalid
     * @throws ClassCastException
     *             if the type is invalid
     */
    void setValue(Object value);
}





A mutable byte wrapper.

   

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Revised from commons lang from Apache
/**
 * A mutable <code>byte</code> wrapper.
 * 
 * @see Byte
 * @since 2.1
 * @version $Id: MutableByte.java 618693 2008-02-05 16:33:29Z sebb $
 */
public class MutableByte extends Number implements Comparable, Mutable {
    /**
     * Required for serialization support.
     * 
     * @see java.io.Serializable
     */
    private static final long serialVersionUID = -1585823265L;
    /** The mutable value. */
    private byte value;
    /**
     * Constructs a new MutableByte with the default value of zero.
     */
    public MutableByte() {
        super();
    }
    /**
     * Constructs a new MutableByte with the specified value.
     * 
     * @param value
     *            a value.
     */
    public MutableByte(byte value) {
        super();
        this.value = value;
    }
    /**
     * Constructs a new MutableByte with the specified value.
     * 
     * @param value
     *            a value.
     * @throws NullPointerException
     *             if the object is null
     */
    public MutableByte(Number value) {
        super();
        this.value = value.byteValue();
    }
    //-----------------------------------------------------------------------
    /**
     * Gets the value as a Byte instance.
     * 
     * @return the value as a Byte
     */
    public Object getValue() {
        return new Byte(this.value);
    }
    /**
     * Sets the value.
     * 
     * @param value
     *            the value to set
     */
    public void setValue(byte value) {
        this.value = value;
    }
    /**
     * Sets the value from any Number instance.
     * 
     * @param value
     *            the value to set
     * @throws NullPointerException
     *             if the object is null
     * @throws ClassCastException
     *             if the type is not a {@link Number}
     */
    public void setValue(Object value) {
        setValue(((Number) value).byteValue());
    }
    //-----------------------------------------------------------------------
    // shortValue relies on Number implementation
    /**
     * Returns the value of this MutableByte as a byte.
     *
     * @return the numeric value represented by this object after conversion to type byte.
     */
    public byte byteValue() {
        return value;
    }
    /**
     * Returns the value of this MutableByte as a int.
     *
     * @return the numeric value represented by this object after conversion to type int.
     */
    public int intValue() {
        return value;
    }
    /**
     * Returns the value of this MutableByte as a long.
     *
     * @return the numeric value represented by this object after conversion to type long.
     */
    public long longValue() {
        return value;
    }
    /**
     * Returns the value of this MutableByte as a float.
     *
     * @return the numeric value represented by this object after conversion to type float.
     */
    public float floatValue() {
        return value;
    }
    /**
     * Returns the value of this MutableByte as a double.
     *
     * @return the numeric value represented by this object after conversion to type double.
     */
    public double doubleValue() {
        return value;
    }
    //-----------------------------------------------------------------------
    /**
     * Gets this mutable as an instance of Byte.
     *
     * @return a Byte instance containing the value from this mutable
     */
    public Byte toByte() {
        return new Byte(byteValue());
    }
    //-----------------------------------------------------------------------
    /**
     * Increments the value.
     *
     * @since Commons Lang 2.2
     */
    public void increment() {
        value++;
    }
    /**
     * Decrements the value.
     *
     * @since Commons Lang 2.2
     */
    public void decrement() {
        value--;
    }
    //-----------------------------------------------------------------------
    /**
     * Adds a value.
     * 
     * @param operand
     *            the value to add
     *
     * @since Commons Lang 2.2
     */
    public void add(byte operand) {
        this.value += operand;
    }
    /**
     * Adds a value.
     * 
     * @param operand
     *            the value to add
     * @throws NullPointerException
     *             if the object is null
     *
     * @since Commons Lang 2.2
     */
    public void add(Number operand) {
        this.value += operand.byteValue();
    }
    /**
     * Subtracts a value.
     * 
     * @param operand
     *            the value to add
     *
     * @since Commons Lang 2.2
     */
    public void subtract(byte operand) {
        this.value -= operand;
    }
    /**
     * Subtracts a value.
     * 
     * @param operand
     *            the value to add
     * @throws NullPointerException
     *             if the object is null
     *
     * @since Commons Lang 2.2
     */
    public void subtract(Number operand) {
        this.value -= operand.byteValue();
    }
    //-----------------------------------------------------------------------
    /**
     * Compares this object against the specified object. The result is <code>true</code> if and only if the argument
     * is not <code>null</code> and is a <code>MutableByte</code> object that contains the same <code>byte</code>
     * value as this object.
     * 
     * @param obj
     *            the object to compare with.
     * @return <code>true</code> if the objects are the same; <code>false</code> otherwise.
     */
    public boolean equals(Object obj) {
        if (obj instanceof MutableByte) {
            return value == ((MutableByte) obj).byteValue();
        }
        return false;
    }
    /**
     * Returns a suitable hashcode for this mutable.
     * 
     * @return a suitable hashcode
     */
    public int hashCode() {
        return value;
    }
    /**
     * Compares this mutable to another in ascending order.
     * 
     * @param obj
     *            the mutable to compare to
     * @return negative if this is less, zero if equal, positive if greater
     * @throws ClassCastException if the argument is not a MutableByte
     */
    public int compareTo(Object obj) {
        MutableByte other = (MutableByte) obj;
        byte anotherVal = other.value;
        return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1);
    }
    /**
     * Returns the String value of this mutable.
     * 
     * @return the mutable value as a string
     */
    public String toString() {
        return String.valueOf(value);
    }
}
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Provides mutable access to a value.
 * <p>
 * <code>Mutable</code> is used as a generic interface to the implementations in this package.
 * <p>
 * A typical use case would be to enable a primitive or string to be passed to a method and allow that method to
 * effectively change the value of the primitive/string. Another use case is to store a frequently changing primitive in
 * a collection (for example a total in a map) without needing to create new Integer/Long wrapper objects.
 * 
 * @author Matthew Hawthorne
 * @since 2.1
 * @version $Id: Mutable.java 618693 2008-02-05 16:33:29Z sebb $
 */
interface Mutable {
    /**
     * Gets the value of this mutable.
     * 
     * @return the stored value
     */
    Object getValue();
    /**
     * Sets the value of this mutable.
     * 
     * @param value
     *            the value to store
     * @throws NullPointerException
     *             if the object is null and null is invalid
     * @throws ClassCastException
     *             if the type is invalid
     */
    void setValue(Object value);
}





A mutable double wrapper.

   
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A mutable <code>double</code> wrapper.
 * 
 * @see Double
 * @since 2.1
 * @version $Id: MutableDouble.java 618693 2008-02-05 16:33:29Z sebb $
 */
public class MutableDouble extends Number implements Comparable, Mutable {
  /**
   * Required for serialization support.
   * 
   * @see java.io.Serializable
   */
  private static final long serialVersionUID = 1587163916L;
  /** The mutable value. */
  private double value;
  /**
   * Constructs a new MutableDouble with the default value of zero.
   */
  public MutableDouble() {
    super();
  }
  /**
   * Constructs a new MutableDouble with the specified value.
   * 
   * @param value
   *          a value.
   */
  public MutableDouble(double value) {
    super();
    this.value = value;
  }
  /**
   * Constructs a new MutableDouble with the specified value.
   * 
   * @param value
   *          a value.
   * @throws NullPointerException
   *           if the object is null
   */
  public MutableDouble(Number value) {
    super();
    this.value = value.doubleValue();
  }
  // -----------------------------------------------------------------------
  /**
   * Gets the value as a Double instance.
   * 
   * @return the value as a Double
   */
  public Object getValue() {
    return new Double(this.value);
  }
  /**
   * Sets the value.
   * 
   * @param value
   *          the value to set
   */
  public void setValue(double value) {
    this.value = value;
  }
  /**
   * Sets the value from any Number instance.
   * 
   * @param value
   *          the value to set
   * @throws NullPointerException
   *           if the object is null
   * @throws ClassCastException
   *           if the type is not a {@link Number}
   */
  public void setValue(Object value) {
    setValue(((Number) value).doubleValue());
  }
  // -----------------------------------------------------------------------
  // shortValue and bytValue rely on Number implementation
  /**
   * Returns the value of this MutableDouble as a int.
   * 
   * @return the numeric value represented by this object after conversion to
   *         type int.
   */
  public int intValue() {
    return (int) value;
  }
  /**
   * Returns the value of this MutableDouble as a long.
   * 
   * @return the numeric value represented by this object after conversion to
   *         type long.
   */
  public long longValue() {
    return (long) value;
  }
  /**
   * Returns the value of this MutableDouble as a float.
   * 
   * @return the numeric value represented by this object after conversion to
   *         type float.
   */
  public float floatValue() {
    return (float) value;
  }
  /**
   * Returns the value of this MutableDouble as a double.
   * 
   * @return the numeric value represented by this object after conversion to
   *         type double.
   */
  public double doubleValue() {
    return value;
  }
  /**
   * Checks whether the double value is the special NaN value.
   * 
   * @return true if NaN
   */
  public boolean isNaN() {
    return Double.isNaN(value);
  }
  /**
   * Checks whether the double value is infinite.
   * 
   * @return true if infinite
   */
  public boolean isInfinite() {
    return Double.isInfinite(value);
  }
  // -----------------------------------------------------------------------
  /**
   * Gets this mutable as an instance of Double.
   * 
   * @return a Double instance containing the value from this mutable
   */
  public Double toDouble() {
    return new Double(doubleValue());
  }
  // -----------------------------------------------------------------------
  /**
   * Increments the value.
   * 
   * @since Commons Lang 2.2
   */
  public void increment() {
    value++;
  }
  /**
   * Decrements the value.
   * 
   * @since Commons Lang 2.2
   */
  public void decrement() {
    value--;
  }
  // -----------------------------------------------------------------------
  /**
   * Adds a value.
   * 
   * @param operand
   *          the value to add
   * 
   * @since Commons Lang 2.2
   */
  public void add(double operand) {
    this.value += operand;
  }
  /**
   * Adds a value.
   * 
   * @param operand
   *          the value to add
   * @throws NullPointerException
   *           if the object is null
   * 
   * @since Commons Lang 2.2
   */
  public void add(Number operand) {
    this.value += operand.doubleValue();
  }
  /**
   * Subtracts a value.
   * 
   * @param operand
   *          the value to add
   * 
   * @since Commons Lang 2.2
   */
  public void subtract(double operand) {
    this.value -= operand;
  }
  /**
   * Subtracts a value.
   * 
   * @param operand
   *          the value to add
   * @throws NullPointerException
   *           if the object is null
   * 
   * @since Commons Lang 2.2
   */
  public void subtract(Number operand) {
    this.value -= operand.doubleValue();
  }
  // -----------------------------------------------------------------------
  /**
   * Compares this object against the specified object. The result is
   * <code>true</code> if and only if the argument is not <code>null</code>
   * and is a <code>Double</code> object that represents a double that has the
   * identical bit pattern to the bit pattern of the double represented by this
   * object. For this purpose, two <code>double</code> values are considered
   * to be the same if and only if the method
   * {@link Double#doubleToLongBits(double)}returns the same long value when
   * applied to each.
   * <p>
   * Note that in most cases, for two instances of class <code>Double</code>,<code>d1</code>
   * and <code>d2</code>, the value of <code>d1.equals(d2)</code> is
   * <code>true</code> if and only if <blockquote>
   * 
   * <pre>
   * d1.doubleValue() == d2.doubleValue()
   * </pre>
   * 
   * </blockquote>
   * <p>
   * also has the value <code>true</code>. However, there are two exceptions:
   * <ul>
   * <li>If <code>d1</code> and <code>d2</code> both represent
   * <code>Double.NaN</code>, then the <code>equals</code> method returns
   * <code>true</code>, even though <code>Double.NaN==Double.NaN</code> has
   * the value <code>false</code>.
   * <li>If <code>d1</code> represents <code>+0.0</code> while
   * <code>d2</code> represents <code>-0.0</code>, or vice versa, the
   * <code>equal</code> test has the value <code>false</code>, even though
   * <code>+0.0==-0.0</code> has the value <code>true</code>. This allows
   * hashtables to operate properly.
   * </ul>
   * 
   * @param obj
   *          the object to compare with.
   * @return <code>true</code> if the objects are the same; <code>false</code>
   *         otherwise.
   */
  public boolean equals(Object obj) {
    return (obj instanceof MutableDouble)
        && (Double.doubleToLongBits(((MutableDouble) obj).value) == Double.doubleToLongBits(value));
  }
  /**
   * Returns a suitable hashcode for this mutable.
   * 
   * @return a suitable hashcode
   */
  public int hashCode() {
    long bits = Double.doubleToLongBits(value);
    return (int) (bits ^ (bits >>> 32));
  }
  /**
   * Compares this mutable to another in ascending order.
   * 
   * @param obj
   *          the mutable to compare to
   * @return negative if this is less, zero if equal, positive if greater
   * @throws ClassCastException
   *           if the argument is not a MutableDouble
   */
  public int compareTo(Object obj) {
    MutableDouble other = (MutableDouble) obj;
    double anotherVal = other.value;
    return compare(value, anotherVal);
  }
  /**
   * Returns the String value of this mutable.
   * 
   * @return the mutable value as a string
   */
  public String toString() {
    return String.valueOf(value);
  }
  protected int compare(Object o1, Object o2) {
    if (o1 == null) {
      if (o2 == null) {
        return 0;
      } else {
        return -((Comparable) o2).rupareTo(o1);
      }
    } else {
      return ((Comparable) o1).rupareTo(o2);
    }
  }
}
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with this
 * work for additional information regarding copyright ownership. The ASF
 * licenses this file to You under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
/**
 * Provides mutable access to a value.
 * <p>
 * <code>Mutable</code> is used as a generic interface to the implementations
 * in this package.
 * <p>
 * A typical use case would be to enable a primitive or string to be passed to a
 * method and allow that method to effectively change the value of the
 * primitive/string. Another use case is to store a frequently changing
 * primitive in a collection (for example a total in a map) without needing to
 * create new Integer/Long wrapper objects.
 * 
 * @author Matthew Hawthorne
 * @since 2.1
 * @version $Id: Mutable.java 618693 2008-02-05 16:33:29Z sebb $
 */
interface Mutable {
  /**
   * Gets the value of this mutable.
   * 
   * @return the stored value
   */
  Object getValue();
  /**
   * Sets the value of this mutable.
   * 
   * @param value
   *          the value to store
   * @throws NullPointerException
   *           if the object is null and null is invalid
   * @throws ClassCastException
   *           if the type is invalid
   */
  void setValue(Object value);
}





A mutable float wrapper.

   
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//Revised from commons lang Apache

/**
 * A mutable <code>float</code> wrapper.
 * 
 * @see Float
 * @since 2.1
 * @version $Id: MutableFloat.java 618693 2008-02-05 16:33:29Z sebb $
 */
public class MutableFloat extends Number implements Comparable, Mutable {
    /**
     * Required for serialization support.
     * 
     * @see java.io.Serializable
     */
    private static final long serialVersionUID = 5787169186L;
    /** The mutable value. */
    private float value;
    /**
     * Constructs a new MutableFloat with the default value of zero.
     */
    public MutableFloat() {
        super();
    }
    /**
     * Constructs a new MutableFloat with the specified value.
     * 
     * @param value
     *            a value.
     */
    public MutableFloat(float value) {
        super();
        this.value = value;
    }
    /**
     * Constructs a new MutableFloat with the specified value.
     * 
     * @param value
     *            a value.
     * @throws NullPointerException
     *             if the object is null
     */
    public MutableFloat(Number value) {
        super();
        this.value = value.floatValue();
    }
    //-----------------------------------------------------------------------
    /**
     * Gets the value as a Float instance.
     * 
     * @return the value as a Float
     */
    public Object getValue() {
        return new Float(this.value);
    }
    /**
     * Sets the value.
     * 
     * @param value
     *            the value to set
     */
    public void setValue(float value) {
        this.value = value;
    }
    /**
     * Sets the value from any Number instance.
     * 
     * @param value
     *            the value to set
     * @throws NullPointerException
     *             if the object is null
     * @throws ClassCastException
     *             if the type is not a {@link Number}
     */
    public void setValue(Object value) {
        setValue(((Number) value).floatValue());
    }
    //-----------------------------------------------------------------------
    /**
     * Increments the value.
     *
     * @since Commons Lang 2.2
     */
    public void increment() {
        value++;
    }
    /**
     * Decrements the value.
     *
     * @since Commons Lang 2.2
     */
    public void decrement() {
        value--;
    }
    //-----------------------------------------------------------------------
    /**
     * Adds a value.
     * 
     * @param operand
     *            the value to add
     *
     * @since Commons Lang 2.2
     */
    public void add(float operand) {
        this.value += operand;
    }
    /**
     * Adds a value.
     * 
     * @param operand
     *            the value to add
     * @throws NullPointerException
     *             if the object is null
     *
     * @since Commons Lang 2.2
     */
    public void add(Number operand) {
        this.value += operand.floatValue();
    }
    /**
     * Subtracts a value.
     * 
     * @param operand
     *            the value to add
     *
     * @since Commons Lang 2.2
     */
    public void subtract(float operand) {
        this.value -= operand;
    }
    /**
     * Subtracts a value.
     * 
     * @param operand
     *            the value to add
     * @throws NullPointerException
     *             if the object is null
     *
     * @since Commons Lang 2.2
     */
    public void subtract(Number operand) {
        this.value -= operand.floatValue();
    }
    //-----------------------------------------------------------------------
    // shortValue and bytValue rely on Number implementation
    /**
     * Returns the value of this MutableFloat as a int.
     *
     * @return the numeric value represented by this object after conversion to type int.
     */
    public int intValue() {
        return (int) value;
    }
    /**
     * Returns the value of this MutableFloat as a long.
     *
     * @return the numeric value represented by this object after conversion to type long.
     */
    public long longValue() {
        return (long) value;
    }
    /**
     * Returns the value of this MutableFloat as a float.
     *
     * @return the numeric value represented by this object after conversion to type float.
     */
    public float floatValue() {
        return value;
    }
    /**
     * Returns the value of this MutableFloat as a double.
     *
     * @return the numeric value represented by this object after conversion to type double.
     */
    public double doubleValue() {
        return value;
    }
    /**
     * Checks whether the float value is the special NaN value.
     * 
     * @return true if NaN
     */
    public boolean isNaN() {
        return Float.isNaN(value);
    }
    /**
     * Checks whether the float value is infinite.
     * 
     * @return true if infinite
     */
    public boolean isInfinite() {
        return Float.isInfinite(value);
    }
    //-----------------------------------------------------------------------
    /**
     * Gets this mutable as an instance of Float.
     *
     * @return a Float instance containing the value from this mutable
     */
    public Float toFloat() {
        return new Float(floatValue());
    }
    //-----------------------------------------------------------------------
    /**
     * Compares this object against some other object. The result is <code>true</code> if and only if the argument is
     * not <code>null</code> and is a <code>Float</code> object that represents a <code>float</code> that has the
     * identical bit pattern to the bit pattern of the <code>float</code> represented by this object. For this
     * purpose, two float values are considered to be the same if and only if the method
     * {@link Float#floatToIntBits(float)}returns the same int value when applied to each.
     * <p>
     * Note that in most cases, for two instances of class <code>Float</code>,<code>f1</code> and <code>f2</code>,
     * the value of <code>f1.equals(f2)</code> is <code>true</code> if and only if <blockquote>
     * 
     * <pre>
     *   f1.floatValue() == f2.floatValue()
     * </pre>
     * 
     * </blockquote>
     * <p>
     * also has the value <code>true</code>. However, there are two exceptions:
     * <ul>
     * <li>If <code>f1</code> and <code>f2</code> both represent <code>Float.NaN</code>, then the
     * <code>equals</code> method returns <code>true</code>, even though <code>Float.NaN==Float.NaN</code> has
     * the value <code>false</code>.
     * <li>If <code>f1</code> represents <code>+0.0f</code> while <code>f2</code> represents <code>-0.0f</code>,
     * or vice versa, the <code>equal</code> test has the value <code>false</code>, even though
     * <code>0.0f==-0.0f</code> has the value <code>true</code>.
     * </ul>
     * This definition allows hashtables to operate properly.
     * 
     * @param obj
     *            the object to be compared
     * @return <code>true</code> if the objects are the same; <code>false</code> otherwise.
     * @see java.lang.Float#floatToIntBits(float)
     */
    public boolean equals(Object obj) {
        return (obj instanceof MutableFloat)
            && (Float.floatToIntBits(((MutableFloat) obj).value) == Float.floatToIntBits(value));
    }
    //-----------------------------------------------------------------------
    /**
     * Returns a suitable hashcode for this mutable.
     * 
     * @return a suitable hashcode
     */
    public int hashCode() {
        return Float.floatToIntBits(value);
    }
    /**
     * Compares this mutable to another in ascending order.
     * 
     * @param obj
     *            the mutable to compare to
     * @return negative if this is less, zero if equal, positive if greater
     */
    public int compareTo(Object obj) {
        MutableFloat other = (MutableFloat) obj;
        float anotherVal = other.value;
        return compare(value, anotherVal);
    }
    protected int compare(Object o1, Object o2) {
      if (o1 == null) {
        if (o2 == null) {
          return 0;
        } else {
          return -((Comparable) o2).rupareTo(o1);
        }
      } else {
        return ((Comparable) o1).rupareTo(o2);
      }
    }
    /**
     * Returns the String value of this mutable.
     * 
     * @return the mutable value as a string
     */
    public String toString() {
        return String.valueOf(value);
    }
}

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with this
 * work for additional information regarding copyright ownership. The ASF
 * licenses this file to You under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
/**
 * Provides mutable access to a value.
 * <p>
 * <code>Mutable</code> is used as a generic interface to the implementations
 * in this package.
 * <p>
 * A typical use case would be to enable a primitive or string to be passed to a
 * method and allow that method to effectively change the value of the
 * primitive/string. Another use case is to store a frequently changing
 * primitive in a collection (for example a total in a map) without needing to
 * create new Integer/Long wrapper objects.
 * 
 * @author Matthew Hawthorne
 * @since 2.1
 * @version $Id: Mutable.java 618693 2008-02-05 16:33:29Z sebb $
 */
interface Mutable {
  /**
   * Gets the value of this mutable.
   * 
   * @return the stored value
   */
  Object getValue();
  /**
   * Sets the value of this mutable.
   * 
   * @param value
   *          the value to store
   * @throws NullPointerException
   *           if the object is null and null is invalid
   * @throws ClassCastException
   *           if the type is invalid
   */
  void setValue(Object value);
}





A mutable int wrapper.

   
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Rwevised from commons lang Apache
/**
 * A mutable <code>int</code> wrapper.
 * 
 * @see Integer
 * @since 2.1
 * @version $Id: MutableInt.java 437554 2006-08-28 06:21:41Z bayard $
 */
public class MutableInt extends Number implements Comparable, Mutable {
    /**
     * Required for serialization support.
     * 
     * @see java.io.Serializable
     */
    private static final long serialVersionUID = 512176391864L;
    /** The mutable value. */
    private int value;
    /**
     * Constructs a new MutableInt with the default value of zero.
     */
    public MutableInt() {
        super();
    }
    /**
     * Constructs a new MutableInt with the specified value.
     * 
     * @param value
     *                  a value.
     */
    public MutableInt(int value) {
        super();
        this.value = value;
    }
    /**
     * Constructs a new MutableInt with the specified value.
     * 
     * @param value
     *                  a value.
     * @throws NullPointerException
     *                  if the object is null
     */
    public MutableInt(Number value) {
        super();
        this.value = value.intValue();
    }
    //-----------------------------------------------------------------------
    /**
     * Gets the value as a Integer instance.
     * 
     * @return the value as a Integer
     */
    public Object getValue() {
        return new Integer(this.value);
    }
    /**
     * Sets the value.
     * 
     * @param value
     *                  the value to set
     */
    public void setValue(int value) {
        this.value = value;
    }
    /**
     * Sets the value from any Number instance.
     * 
     * @param value
     *                  the value to set
     * @throws NullPointerException
     *                  if the object is null
     * @throws ClassCastException
     *                  if the type is not a {@link Number}
     */
    public void setValue(Object value) {
        setValue(((Number) value).intValue());
    }
    //-----------------------------------------------------------------------
    /**
     * Increments the value.
     *
     * @since Commons Lang 2.2
     */
    public void increment() {
        value++;
    }
    /**
     * Decrements the value.
     *
     * @since Commons Lang 2.2
     */
    public void decrement() {
        value--;
    }
    //-----------------------------------------------------------------------
    /**
     * Adds a value.
     * 
     * @param operand
     *            the value to add
     *
     * @since Commons Lang 2.2
     */
    public void add(int operand) {
        this.value += operand;
    }
    /**
     * Adds a value.
     * 
     * @param operand
     *            the value to add
     * @throws NullPointerException
     *             if the object is null
     *
     * @since Commons Lang 2.2
     */
    public void add(Number operand) {
        this.value += operand.intValue();
    }
    /**
     * Subtracts a value.
     * 
     * @param operand
     *            the value to add
     *
     * @since Commons Lang 2.2
     */
    public void subtract(int operand) {
        this.value -= operand;
    }
    /**
     * Subtracts a value.
     * 
     * @param operand
     *            the value to add
     * @throws NullPointerException
     *             if the object is null
     *
     * @since Commons Lang 2.2
     */
    public void subtract(Number operand) {
        this.value -= operand.intValue();
    }
    //-----------------------------------------------------------------------
    // shortValue and bytValue rely on Number implementation
    /**
     * Returns the value of this MutableInt as a int.
     *
     * @return the numeric value represented by this object after conversion to type int.
     */
    public int intValue() {
        return value;
    }
    /**
     * Returns the value of this MutableInt as a long.
     *
     * @return the numeric value represented by this object after conversion to type long.
     */
    public long longValue() {
        return value;
    }
    /**
     * Returns the value of this MutableInt as a float.
     *
     * @return the numeric value represented by this object after conversion to type float.
     */
    public float floatValue() {
        return value;
    }
    /**
     * Returns the value of this MutableInt as a double.
     *
     * @return the numeric value represented by this object after conversion to type double.
     */
    public double doubleValue() {
        return value;
    }
    //-----------------------------------------------------------------------
    /**
     * Gets this mutable as an instance of Integer.
     *
     * @return a Integer instance containing the value from this mutable
     */
    public Integer toInteger() {
        return new Integer(intValue());
    }
    //-----------------------------------------------------------------------
    /**
     * Compares this object to the specified object. The result is <code>true</code> if and only if the argument is
     * not <code>null</code> and is an <code>MutableInt</code> object that contains the same <code>int</code> value
     * as this object.
     * 
     * @param obj
     *                  the object to compare with.
     * @return <code>true</code> if the objects are the same; <code>false</code> otherwise.
     */
    public boolean equals(Object obj) {
        if (obj instanceof MutableInt) {
            return value == ((MutableInt) obj).intValue();
        }
        return false;
    }
    /**
     * Returns a suitable hashcode for this mutable.
     * 
     * @return a suitable hashcode
     */
    public int hashCode() {
        return value;
    }
    /**
     * Compares this mutable to another in ascending order.
     * 
     * @param obj
     *                  the mutable to compare to
     * @return negative if this is less, zero if equal, positive if greater
     * @throws ClassCastException if the argument is not a MutableInt
     */
    public int compareTo(Object obj) {
        MutableInt other = (MutableInt) obj;
        int anotherVal = other.value;
        return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1);
    }
    /**
     * Returns the String value of this mutable.
     * 
     * @return the mutable value as a string
     */
    public String toString() {
        return String.valueOf(value);
    }
}
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with this
 * work for additional information regarding copyright ownership. The ASF
 * licenses this file to You under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
/**
 * Provides mutable access to a value.
 * <p>
 * <code>Mutable</code> is used as a generic interface to the implementations
 * in this package.
 * <p>
 * A typical use case would be to enable a primitive or string to be passed to a
 * method and allow that method to effectively change the value of the
 * primitive/string. Another use case is to store a frequently changing
 * primitive in a collection (for example a total in a map) without needing to
 * create new Integer/Long wrapper objects.
 * 
 * @author Matthew Hawthorne
 * @since 2.1
 * @version $Id: Mutable.java 618693 2008-02-05 16:33:29Z sebb $
 */
interface Mutable {
  /**
   * Gets the value of this mutable.
   * 
   * @return the stored value
   */
  Object getValue();
  /**
   * Sets the value of this mutable.
   * 
   * @param value
   *          the value to store
   * @throws NullPointerException
   *           if the object is null and null is invalid
   * @throws ClassCastException
   *           if the type is invalid
   */
  void setValue(Object value);
}





A mutable long wrapper.

   
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Revised from commons lang Apache
/**
 * A mutable <code>long</code> wrapper.
 * 
 * @see Long
 * @since 2.1
 * @version $Id: MutableLong.java 618693 2008-02-05 16:33:29Z sebb $
 */
public class MutableLong extends Number implements Comparable, Mutable {
    /**
     * Required for serialization support.
     * 
     * @see java.io.Serializable
     */
    private static final long serialVersionUID = 62986528375L;
    /** The mutable value. */
    private long value;
    /**
     * Constructs a new MutableLong with the default value of zero.
     */
    public MutableLong() {
        super();
    }
    /**
     * Constructs a new MutableLong with the specified value.
     * 
     * @param value
     *            a value.
     */
    public MutableLong(long value) {
        super();
        this.value = value;
    }
    /**
     * Constructs a new MutableLong with the specified value.
     * 
     * @param value
     *            a value.
     * @throws NullPointerException
     *             if the object is null
     */
    public MutableLong(Number value) {
        super();
        this.value = value.longValue();
    }
    //-----------------------------------------------------------------------
    /**
     * Gets the value as a Long instance.
     * 
     * @return the value as a Long
     */
    public Object getValue() {
        return new Long(this.value);
    }
    /**
     * Sets the value.
     * 
     * @param value
     *            the value to set
     */
    public void setValue(long value) {
        this.value = value;
    }
    /**
     * Sets the value from any Number instance.
     * 
     * @param value
     *            the value to set
     * @throws NullPointerException
     *             if the object is null
     * @throws ClassCastException
     *             if the type is not a {@link Number}
     */
    public void setValue(Object value) {
        setValue(((Number) value).longValue());
    }
    //-----------------------------------------------------------------------
    /**
     * Increments the value.
     *
     * @since Commons Lang 2.2
     */
    public void increment() {
        value++;
    }
    /**
     * Decrements the value.
     *
     * @since Commons Lang 2.2
     */
    public void decrement() {
        value--;
    }
    //-----------------------------------------------------------------------
    /**
     * Adds a value.
     * 
     * @param operand
     *            the value to add
     *
     * @since Commons Lang 2.2
     */
    public void add(long operand) {
        this.value += operand;
    }
    /**
     * Adds a value.
     * 
     * @param operand
     *            the value to add
     * @throws NullPointerException
     *             if the object is null
     *
     * @since Commons Lang 2.2
     */
    public void add(Number operand) {
        this.value += operand.longValue();
    }
    /**
     * Subtracts a value.
     * 
     * @param operand
     *            the value to add
     *
     * @since Commons Lang 2.2
     */
    public void subtract(long operand) {
        this.value -= operand;
    }
    /**
     * Subtracts a value.
     * 
     * @param operand
     *            the value to add
     * @throws NullPointerException
     *             if the object is null
     *
     * @since Commons Lang 2.2
     */
    public void subtract(Number operand) {
        this.value -= operand.longValue();
    }
    //-----------------------------------------------------------------------
    // shortValue and bytValue rely on Number implementation
    /**
     * Returns the value of this MutableLong as a int.
     *
     * @return the numeric value represented by this object after conversion to type int.
     */
    public int intValue() {
        return (int) value;
    }
    /**
     * Returns the value of this MutableLong as a long.
     *
     * @return the numeric value represented by this object after conversion to type long.
     */
    public long longValue() {
        return value;
    }
    /**
     * Returns the value of this MutableLong as a float.
     *
     * @return the numeric value represented by this object after conversion to type float.
     */
    public float floatValue() {
        return value;
    }
    /**
     * Returns the value of this MutableLong as a double.
     *
     * @return the numeric value represented by this object after conversion to type double.
     */
    public double doubleValue() {
        return value;
    }
    //-----------------------------------------------------------------------
    /**
     * Gets this mutable as an instance of Long.
     *
     * @return a Long instance containing the value from this mutable
     */
    public Long toLong() {
        return new Long(longValue());
    }
    //-----------------------------------------------------------------------
    /**
     * Compares this object against the specified object. The result is <code>true</code> if and only if the argument
     * is not <code>null</code> and is a <code>MutableLong</code> object that contains the same <code>long</code>
     * value as this object.
     * 
     * @param obj
     *            the object to compare with.
     * @return <code>true</code> if the objects are the same; <code>false</code> otherwise.
     */
    public boolean equals(Object obj) {
        if (obj instanceof MutableLong) {
            return value == ((MutableLong) obj).longValue();
        }
        return false;
    }
    /**
     * Returns a suitable hashcode for this mutable.
     * 
     * @return a suitable hashcode
     */
    public int hashCode() {
        return (int) (value ^ (value >>> 32));
    }
    /**
     * Compares this mutable to another in ascending order.
     * 
     * @param obj
     *            the mutable to compare to
     * @return negative if this is less, zero if equal, positive if greater
     * @throws ClassCastException if the argument is not a MutableLong
     */
    public int compareTo(Object obj) {
        MutableLong other = (MutableLong) obj;
        long anotherVal = other.value;
        return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1);
    }
    /**
     * Returns the String value of this mutable.
     * 
     * @return the mutable value as a string
     */
    public String toString() {
        return String.valueOf(value);
    }
}
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with this
 * work for additional information regarding copyright ownership. The ASF
 * licenses this file to You under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
/**
 * Provides mutable access to a value.
 * <p>
 * <code>Mutable</code> is used as a generic interface to the implementations
 * in this package.
 * <p>
 * A typical use case would be to enable a primitive or string to be passed to a
 * method and allow that method to effectively change the value of the
 * primitive/string. Another use case is to store a frequently changing
 * primitive in a collection (for example a total in a map) without needing to
 * create new Integer/Long wrapper objects.
 * 
 * @author Matthew Hawthorne
 * @since 2.1
 * @version $Id: Mutable.java 618693 2008-02-05 16:33:29Z sebb $
 */
interface Mutable {
  /**
   * Gets the value of this mutable.
   * 
   * @return the stored value
   */
  Object getValue();
  /**
   * Sets the value of this mutable.
   * 
   * @param value
   *          the value to store
   * @throws NullPointerException
   *           if the object is null and null is invalid
   * @throws ClassCastException
   *           if the type is invalid
   */
  void setValue(Object value);
}





A mutable short wrapper.

   
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Revised from commons math Apache
/**
 * A mutable <code>short</code> wrapper.
 * 
 * @see Short
 * @since 2.1
 * @version $Id: MutableShort.java 618693 2008-02-05 16:33:29Z sebb $
 */
public class MutableShort extends Number implements Comparable, Mutable {
    /**
     * Required for serialization support.
     * 
     * @see java.io.Serializable
     */
    private static final long serialVersionUID = -2135791679L;
    /** The mutable value. */
    private short value;
    /**
     * Constructs a new MutableShort with the default value of zero.
     */
    public MutableShort() {
        super();
    }
    /**
     * Constructs a new MutableShort with the specified value.
     * 
     * @param value
     *                  a value.
     */
    public MutableShort(short value) {
        super();
        this.value = value;
    }
    /**
     * Constructs a new MutableShort with the specified value.
     * 
     * @param value
     *                  a value.
     * @throws NullPointerException
     *                  if the object is null
     */
    public MutableShort(Number value) {
        super();
        this.value = value.shortValue();
    }
    //-----------------------------------------------------------------------
    /**
     * Gets the value as a Short instance.
     * 
     * @return the value as a Short
     */
    public Object getValue() {
        return new Short(this.value);
    }
    /**
     * Sets the value.
     * 
     * @param value
     *                  the value to set
     */
    public void setValue(short value) {
        this.value = value;
    }
    /**
     * Sets the value from any Number instance.
     * 
     * @param value
     *                  the value to set
     * @throws NullPointerException
     *                  if the object is null
     * @throws ClassCastException
     *                  if the type is not a {@link Number}
     */
    public void setValue(Object value) {
        setValue(((Number) value).shortValue());
    }
    //-----------------------------------------------------------------------
    /**
     * Increments the value.
     *
     * @since Commons Lang 2.2
     */
    public void increment() {
        value++;
    }
    /**
     * Decrements the value.
     *
     * @since Commons Lang 2.2
     */
    public void decrement() {
        value--;
    }
    //-----------------------------------------------------------------------
    /**
     * Adds a value.
     * 
     * @param operand
     *            the value to add
     *
     * @since Commons Lang 2.2
     */
    public void add(short operand) {
        this.value += operand;
    }
    /**
     * Adds a value.
     * 
     * @param operand
     *            the value to add
     * @throws NullPointerException
     *             if the object is null
     *
     * @since Commons Lang 2.2
     */
    public void add(Number operand) {
        this.value += operand.shortValue();
    }
    /**
     * Subtracts a value.
     * 
     * @param operand
     *            the value to add
     *
     * @since Commons Lang 2.2
     */
    public void subtract(short operand) {
        this.value -= operand;
    }
    /**
     * Subtracts a value.
     * 
     * @param operand
     *            the value to add
     * @throws NullPointerException
     *             if the object is null
     *
     * @since Commons Lang 2.2
     */
    public void subtract(Number operand) {
        this.value -= operand.shortValue();
    }
    //-----------------------------------------------------------------------
    // bytValue relies on Number implementation
    /**
     * Returns the value of this MutableShort as a short.
     *
     * @return the numeric value represented by this object after conversion to type short.
     */
    public short shortValue() {
        return value;
    }
    /**
     * Returns the value of this MutableShort as a int.
     *
     * @return the numeric value represented by this object after conversion to type int.
     */
    public int intValue() {
        return value;
    }
    /**
     * Returns the value of this MutableShort as a long.
     *
     * @return the numeric value represented by this object after conversion to type long.
     */
    public long longValue() {
        return value;
    }
    /**
     * Returns the value of this MutableShort as a float.
     *
     * @return the numeric value represented by this object after conversion to type float.
     */
    public float floatValue() {
        return value;
    }
    /**
     * Returns the value of this MutableShort as a double.
     *
     * @return the numeric value represented by this object after conversion to type double.
     */
    public double doubleValue() {
        return value;
    }
    //-----------------------------------------------------------------------
    /**
     * Gets this mutable as an instance of Short.
     *
     * @return a Short instance containing the value from this mutable
     */
    public Short toShort() {
        return new Short(shortValue());
    }
    //-----------------------------------------------------------------------
    /**
     * Compares this object against the specified object. The result is <code>true</code> if and only if the argument
     * is not <code>null</code> and is a <code>MutableShort</code> object that contains the same <code>short</code>
     * value as this object.
     * 
     * @param obj
     *                  the object to compare with.
     * @return <code>true</code> if the objects are the same; <code>false</code> otherwise.
     */
    public boolean equals(Object obj) {
        if (obj instanceof MutableShort) {
            return value == ((MutableShort) obj).shortValue();
        }
        return false;
    }
    /**
     * Returns a suitable hashcode for this mutable.
     * 
     * @return a suitable hashcode
     */
    public int hashCode() {
        return value;
    }
    /**
     * Compares this mutable to another in ascending order.
     * 
     * @param obj
     *                  the mutable to compare to
     * @return negative if this is less, zero if equal, positive if greater
     * @throws ClassCastException if the argument is not a MutableShort
     */
    public int compareTo(Object obj) {
        MutableShort other = (MutableShort) obj;
        short anotherVal = other.value;
        return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1);
    }
    /**
     * Returns the String value of this mutable.
     * 
     * @return the mutable value as a string
     */
    public String toString() {
        return String.valueOf(value);
    }
}

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Provides mutable access to a value.
 * <p>
 * <code>Mutable</code> is used as a generic interface to the implementations in this package.
 * <p>
 * A typical use case would be to enable a primitive or string to be passed to a method and allow that method to
 * effectively change the value of the primitive/string. Another use case is to store a frequently changing primitive in
 * a collection (for example a total in a map) without needing to create new Integer/Long wrapper objects.
 * 
 * @author Matthew Hawthorne
 * @since 2.1
 * @version $Id: Mutable.java 618693 2008-02-05 16:33:29Z sebb $
 */
interface Mutable {
    /**
     * Gets the value of this mutable.
     * 
     * @return the stored value
     */
    Object getValue();
    /**
     * Sets the value of this mutable.
     * 
     * @param value
     *            the value to store
     * @throws NullPointerException
     *             if the object is null and null is invalid
     * @throws ClassCastException
     *             if the type is invalid
     */
    void setValue(Object value);
}





Arithmetic Demo

     
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
public class ArithmeticDemo {
    public static void main(String[] args) {
        //a few numbers
        int i = 37;
        int j = 42;
        double x = 27.475;
        double y = 7.22;
        System.out.println("Variable values...");
        System.out.println("    i = " + i);
        System.out.println("    j = " + j);
        System.out.println("    x = " + x);
        System.out.println("    y = " + y);
        //adding numbers
        System.out.println("Adding...");
        System.out.println("    i + j = " + (i + j));
        System.out.println("    x + y = " + (x + y));
        //subtracting numbers
        System.out.println("Subtracting...");
        System.out.println("    i - j = " + (i - j));
        System.out.println("    x - y = " + (x - y));
        //multiplying numbers
        System.out.println("Multiplying...");
        System.out.println("    i * j = " + (i * j));
        System.out.println("    x * y = " + (x * y));
        //dividing numbers
        System.out.println("Dividing...");
        System.out.println("    i / j = " + (i / j));
        System.out.println("    x / y = " + (x / y));
        //computing the remainder resulting from dividing numbers
        System.out.println("Computing the remainder...");
        System.out.println("    i % j = " + (i % j));
        System.out.println("    x % y = " + (x % y));
        //mixing types
        System.out.println("Mixing types...");
        System.out.println("    j + y = " + (j + y));
        System.out.println("    i * x = " + (i * x));
    }
}





Built in types

     
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
/**
 * Built in types
 */
public class BuiltinTypes {
  public static void main(String[] argv) {
    // An integer can be entered in several ways:
    int i = 123;
    System.out.println("i = " + i);
    i = 00123;
    System.out.println("i = " + i);
    i = 0x123;
    System.out.println("i = " + i);
    // A double can also be entered in several ways:
    float f = 123f;
    System.out.println("f = " + f);
    f = 123.0f;
    System.out.println("f = " + f);
    f = (float)1.23e2;    // 1.23 x (10 ^ 2)
    System.out.println("f = " + f);
  }
}





Convert Java Integer object to Numeric primitive types

     
public class Main {
  public static void main(String[] args) {
    Integer intObj = new Integer("10");
    byte b = intObj.byteValue();
    System.out.println(b);
    short s = intObj.shortValue();
    System.out.println(s);
    int i = intObj.intValue();
    System.out.println(i);
    float f = intObj.floatValue();
    System.out.println(f);
    double d = intObj.doubleValue();
    System.out.println(d);
  }
}





Convert Java String to Integer object

     

public class Main {
  public static void main(String[] args) {
    Integer intObj1 = new Integer("100");
    System.out.println(intObj1);
    String str = "100";
    Integer intObj2 = Integer.valueOf(str);
    System.out.println(intObj2);
  }
}





Convert primitive back and forth

  

public final class PrimitiveUtils {
    
    public static Class getClass(String value) {
        Class clz = null;        
        if ("int".equals(value)) {
            clz = int.class;
        }
        if ("byte".equals(value)) {
            clz = byte.class;
        }
        if ("short".equals(value)) {
            clz = short.class;
        }
        if ("long".equals(value)) {
            clz = long.class;
        }
        if ("float".equals(value)) {
            clz = float.class;
        }
        if ("double".equals(value)) {
            clz = double.class;
        }
        if ("boolean".equals(value)) {
            clz = boolean.class;
        }
        if ("char".equals(value)) {
            clz = char.class;
        }
        return clz;
    }
    public static Object read(String value, Class type) {
        Object ret = value;
        if (Integer.TYPE.equals(type)) {
            ret = Integer.valueOf(value);
        }
        if (Byte.TYPE.equals(type)) {
            ret = Byte.valueOf(value);
        }
        if (Short.TYPE.equals(type)) {
            ret = Short.valueOf(value);
        }
        if (Long.TYPE.equals(type)) {
            ret = Long.valueOf(value);
        }
        if (Float.TYPE.equals(type)) {
            ret = Float.valueOf(value);
        }
        if (Double.TYPE.equals(type)) {
            ret = Double.valueOf(value);
        }
        if (Boolean.TYPE.equals(type)) {
            ret = Boolean.valueOf(value);
        }
        if (Character.TYPE.equals(type)) {
            ret = value.charAt(0);
        }
        // TODO others.
        return ret;
    }
}





Convert the given array (which may be a primitive array) to an object array

     
import java.lang.reflect.Array;
import java.util.Arrays;
/*
 * Copyright 2002-2007 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//Revised from springframework
/**
 * Miscellaneous object utility methods. Mainly for internal use within the
 * framework; consider Jakarta"s Commons Lang for a more comprehensive suite
 * of object utilities.
 *
 * @author Juergen Hoeller
 * @author Keith Donald
 * @author Rod Johnson
 * @author Rob Harrop
 * @author Alex Ruiz
 * @since 19.03.2004
 * @see org.apache.rumons.lang.ObjectUtils
 */
abstract class ObjectUtils {
  private static final int INITIAL_HASH = 7;
  private static final int MULTIPLIER = 31;
  private static final String EMPTY_STRING = "";
  private static final String NULL_STRING = "null";
  private static final String ARRAY_START = "{";
  private static final String ARRAY_END = "}";
  private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
  private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
  /**
   * Return whether the given array is empty: that is, <code>null</code>
   * or of zero length.
   * @param array the array to check
   * @return whether the given array is empty
   */
  public static boolean isEmpty(Object[] array) {
    return (array == null || array.length == 0);
  }
  /**
   * Append the given Object to the given array, returning a new array
   * consisting of the input array contents plus the given Object.
   * @param array the array to append to (can be <code>null</code>)
   * @param obj the Object to append
   * @return the new array (of the same component type; never <code>null</code>)
   */
  public static Object[] addObjectToArray(Object[] array, Object obj) {
    Class compType = Object.class;
    if (array != null) {
      compType = array.getClass().getComponentType();
    }
    else if (obj != null) {
      compType = obj.getClass();
    }
    int newArrLength = (array != null ? array.length + 1 : 1);
    Object[] newArr = (Object[]) Array.newInstance(compType, newArrLength);
    if (array != null) {
      System.arraycopy(array, 0, newArr, 0, array.length);
    }
    newArr[newArr.length - 1] = obj;
    return newArr;
  }
  /**
   * Convert the given array (which may be a primitive array) to an
   * object array (if necessary of primitive wrapper objects).
   * <p>A <code>null</code> source value will be converted to an
   * empty Object array.
   * @param source the (potentially primitive) array
   * @return the corresponding object array (never <code>null</code>)
   * @throws IllegalArgumentException if the parameter is not an array
   */
  public static Object[] toObjectArray(Object source) {
    if (source instanceof Object[]) {
      return (Object[]) source;
    }
    if (source == null) {
      return new Object[0];
    }
    if (!source.getClass().isArray()) {
      throw new IllegalArgumentException("Source is not an array: " + source);
    }
    int length = Array.getLength(source);
    if (length == 0) {
      return new Object[0];
    }
    Class wrapperType = Array.get(source, 0).getClass();
    Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
    for (int i = 0; i < length; i++) {
      newArray[i] = Array.get(source, i);
    }
    return newArray;
  }

}





Create an Integer object

     
public class Main {
  public static void main(String[] args) {
    Integer intObj1 = new Integer(10);
    Integer intObj2 = new Integer("10");
    System.out.println(intObj1);
    System.out.println(intObj2);
  }
}





Data Type Print Test

     
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
public class DataTypePrintTest {
    public static void main(String[] args) {
        Thread objectData = new Thread();
        String stringData = "Java Mania";
        char[] charArrayData = { "a", "b", "c" };
        int integerData = 4;
        long longData = Long.MIN_VALUE;
        float floatData = Float.MAX_VALUE;
        double doubleData = Math.PI;
        boolean booleanData = true;
        System.out.println(objectData);
        System.out.println(stringData);
        System.out.println(charArrayData);
        System.out.println(integerData);
        System.out.println(longData);
        System.out.println(floatData);
        System.out.println(doubleData);
        System.out.println(booleanData);
    }
}





Demonstrates the ++ and -- operators

     
//: c03:AutoInc.java
// Demonstrates the ++ and -- operators.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class AutoInc {
  public static void main(String[] args) {
    int i = 1;
    System.out.println("i : " + i);
    System.out.println("++i : " + ++i); // Pre-increment
    System.out.println("i++ : " + i++); // Post-increment
    System.out.println("i : " + i);
    System.out.println("--i : " + --i); // Pre-decrement
    System.out.println("i-- : " + i--); // Post-decrement
    System.out.println("i : " + i);
  }
} ///:~





Demonstrates the mathematical operators.

     
//: c03:MathOps.java
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.*;
public class MathOps {
  // Shorthand to print a string and an int:
  static void printInt(String s, int i) {
    System.out.println(s + " = " + i);
  }
  // Shorthand to print a string and a float:
  static void printFloat(String s, float f) {
    System.out.println(s + " = " + f);
  }
  public static void main(String[] args) {
    // Create a random number generator,
    // seeds with current time by default:
    Random rand = new Random();
    int i, j, k;
    // Choose value from 1 to 100:
    j = rand.nextInt(100) + 1;
    k = rand.nextInt(100) + 1;
    printInt("j", j);  printInt("k", k);
    i = j + k; printInt("j + k", i);
    i = j - k; printInt("j - k", i);
    i = k / j; printInt("k / j", i);
    i = k * j; printInt("k * j", i);
    i = k % j; printInt("k % j", i);
    j %= k; printInt("j %= k", j);
    // Floating-point number tests:
    float u,v,w;  // applies to doubles, too
    v = rand.nextFloat();
    w = rand.nextFloat();
    printFloat("v", v); printFloat("w", w);
    u = v + w; printFloat("v + w", u);
    u = v - w; printFloat("v - w", u);
    u = v * w; printFloat("v * w", u);
    u = v / w; printFloat("v / w", u);
    // the following also works for
    // char, byte, short, int, long,
    // and double:
    u += v; printFloat("u += v", u);
    u -= v; printFloat("u -= v", u);
    u *= v; printFloat("u *= v", u);
    u /= v; printFloat("u /= v", u);
  }
} ///:~





Java lets you overflow

     
//: c03:Overflow.java
// Surprise! Java lets you overflow.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.

public class Overflow {

  public static void main(String[] args) {
    int big = 0x7fffffff; // max int value
    System.out.println("big = " + big);
    int bigger = big * 4;
    System.out.println("bigger = " + bigger);

  }
} ///:~





Java Type Helper

    
/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the "License").  You may not use this file except 
 * in compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * glassfish/bootstrap/legal/CDDLv1.0.txt or 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html. 
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * HEADER in each file and include the License file at 
 * glassfish/bootstrap/legal/CDDLv1.0.txt.  If applicable, 
 * add the following below this CDDL HEADER, with the 
 * fields enclosed by brackets "[]" replaced with your 
 * own identifying information: Portions Copyright [yyyy] 
 * [name of copyright owner]
 */
/*
 * JavaTypeHelper.java
 *
 * Created on January 22, 2002, 3:39 PM
 */

import java.util.HashMap;
import java.util.Map;
/**
 * This is a helper class which provides some basic java type convenience
 * methods: extraction of a package from a fully qualified class name,
 * extraction of a short (non-qualified) name from a fully qualified class name,
 * and various wrapper and primitive type methods.
 * @author Rochelle Raccah
 */
public class JavaTypeHelper {
    /**
     * Map of primitive to wrapper classes
     */
    private final static Map _primitiveToWrappers;
    /**
     * Map of primitive names to primitive classes
     */
    private final static Map _primitiveNamesToPrimitives;
    /**
     * Map of primitive names to wrapper names
     */
    private final static Map _primitiveNamesToWrapperNames;
    /**
     * Map of wrapper classes to primitive names
     */
    private final static Map _wrapperToPrimitiveNames;
    static {
        _primitiveToWrappers = new HashMap(9);
        _primitiveToWrappers.put(Boolean.TYPE, Boolean.class);
        _primitiveToWrappers.put(Byte.TYPE, Byte.class);
        _primitiveToWrappers.put(Character.TYPE, Character.class);
        _primitiveToWrappers.put(Double.TYPE, Double.class);
        _primitiveToWrappers.put(Float.TYPE, Float.class);
        _primitiveToWrappers.put(Integer.TYPE, Integer.class);
        _primitiveToWrappers.put(Long.TYPE, Long.class);
        _primitiveToWrappers.put(Short.TYPE, Short.class);
        _primitiveToWrappers.put(Void.TYPE, Void.class);
        _primitiveNamesToPrimitives = new HashMap(9);
        _primitiveNamesToPrimitives.put("boolean", Boolean.TYPE); // NOI18N
        _primitiveNamesToPrimitives.put("byte", Byte.TYPE);     // NOI18N
        _primitiveNamesToPrimitives.put("char", Character.TYPE);  // NOI18N
        _primitiveNamesToPrimitives.put("double", Double.TYPE);   // NOI18N
        _primitiveNamesToPrimitives.put("float", Float.TYPE);   // NOI18N
        _primitiveNamesToPrimitives.put("int", Integer.TYPE);   // NOI18N
        _primitiveNamesToPrimitives.put("long", Long.TYPE);     // NOI18N
        _primitiveNamesToPrimitives.put("short", Short.TYPE);   // NOI18N
        _primitiveNamesToPrimitives.put("void", Void.TYPE);     // NOI18N
        _primitiveNamesToWrapperNames = new HashMap(9);
        _primitiveNamesToWrapperNames.put("boolean", "Boolean");  // NOI18N
        _primitiveNamesToWrapperNames.put("byte", "Byte");      // NOI18N
        _primitiveNamesToWrapperNames.put("char", "Character");   // NOI18N
        _primitiveNamesToWrapperNames.put("double", "Double");    // NOI18N
        _primitiveNamesToWrapperNames.put("float", "Float");    // NOI18N
        _primitiveNamesToWrapperNames.put("int", "Integer");    // NOI18N
        _primitiveNamesToWrapperNames.put("long", "Long");      // NOI18N
        _primitiveNamesToWrapperNames.put("short", "Short");    // NOI18N
        _primitiveNamesToWrapperNames.put("void", "Void");      // NOI18N
        _wrapperToPrimitiveNames = new HashMap(9);
        _wrapperToPrimitiveNames.put(Boolean.class, "boolean"); // NOI18N
        _wrapperToPrimitiveNames.put(Byte.class, "byte");   // NOI18N
        _wrapperToPrimitiveNames.put(Character.class, "char");  // NOI18N
        _wrapperToPrimitiveNames.put(Double.class, "double"); // NOI18N
        _wrapperToPrimitiveNames.put(Float.class, "float");   // NOI18N
        _wrapperToPrimitiveNames.put(Integer.class, "int");   // NOI18N
        _wrapperToPrimitiveNames.put(Long.class, "long");   // NOI18N
        _wrapperToPrimitiveNames.put(Short.class, "short");   // NOI18N
        _wrapperToPrimitiveNames.put(Void.class, "void");   // NOI18N
    }
    /**
     * Returns the package portion of the specified class
     * @param className the name of the class from which to extract the package
     * @return package portion of the specified class
     */
    public static String getPackageName(final String className) {
        if (className != null) {
            final int index = className.lastIndexOf(".");
            return ((index != -1) ? className.substring(0, index) : ""); // NOI18N
        }
        return null;
    }
    /**
     * Returns the name of a class without the package name.  For example: if
     * input = "java.lang.Object" , then output = "Object".
     * @param fully qualified classname
     */
    public static String getShortClassName(final String className) {
        if (className != null) {
            final int index = className.lastIndexOf(".");
            return className.substring(index + 1);
        }
        return null;
    }
    // primitive/wrapper class utilities
    /**
     * Returns the wrapper class associated with the supplied primitive class.
     * @param primitive the primitive class to be used for lookup.
     * @return the associated wrapper class.
     */
    public static Class getWrapperClass(Class primitive) {
        return (Class) _primitiveToWrappers.get(primitive);
    }
    /**
     * Returns the primitive class associated with the supplied primitive type
     * name.
     * @param primitiveName the name of the primitive to be used for lookup.
     * @return the associated primitive class.
     */
    public static Class getPrimitiveClass(String primitiveName) {
        return (Class) _primitiveNamesToPrimitives.get(primitiveName);
    }
    /**
     * Returns the name of the wrapper class associated with the supplied
     * primitive type name.
     * @param primitiveName the name of the primitive to be used for lookup.
     * @return the associated wrapper class name.
     */
    public static String getWrapperName(String primitiveName) {
        return (String) _primitiveNamesToWrapperNames.get(primitiveName);
    }
    /**
     * Returns the name of the primitive type associated with the supplied
     * wrapper class.
     * @param wrapper the wrapper class to be used for lookup.
     * @return the associated primitive type name.
     */
    public static String getPrimitiveName(Class wrapper) {
        return (String) _wrapperToPrimitiveNames.get(wrapper);
    }
    /**
     * Returns the Boolean wrapper object for true or false corresponding to the
     * supplied argument.  This is to provide a convenience method for this
     * conversion but to prevent calling the Boolean constructor which has been
     * determined to be unnecessary and a performance problem.  JDK 1.4 provides
     * such a method, but some of our code still works with JDK 1.3.
     * @param flag the primitive boolean object to be translated to a Boolean
     * wrapper.
     * @return the associated true/false shared wrapper object
     */
    public static Boolean valueOf(boolean flag) {
        return (flag ? Boolean.TRUE : Boolean.FALSE);
    }
}





Literals

     
//: c03:Literals.java
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class Literals {
  
  char c = 0xffff; // max char hex value
  
  byte b = 0x7f; // max byte hex value
  
  short s = 0x7fff; // max short hex value
  
  int i1 = 0x2f; // Hexadecimal (lowercase)
  
  int i2 = 0X2F; // Hexadecimal (uppercase)
  
  int i3 = 0177; // Octal (leading zero)
  
  // Hex and Oct also work with long.
  
  long n1 = 200L; // long suffix
  long n2 = 200l; // long suffix (but can be confusing)
  long n3 = 200;
  //! long l6(200); // not allowed
  float f1 = 1;
  float f2 = 1F; // float suffix
  float f3 = 1f; // float suffix
  float f4 = 1e-45f; // 10 to the power
  float f5 = 1e+9f; // float suffix
  double d1 = 1d; // double suffix
  double d2 = 1D; // double suffix
  double d3 = 47e47d; // 10 to the power
} ///:~





Max Variable Length Demo

     
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
public class MaxVariablesDemo {
    public static void main(String args[]) {
        // integers
        byte largestByte = Byte.MAX_VALUE;
        short largestShort = Short.MAX_VALUE;
        int largestInteger = Integer.MAX_VALUE;
        long largestLong = Long.MAX_VALUE;
        /* real numbers*/
        float largestFloat = Float.MAX_VALUE;
        double largestDouble = Double.MAX_VALUE;
        // other primitive types
        char aChar = "S";
        boolean aBoolean = true;
        // display them all
        System.out.println("The largest byte value is " + largestByte);
        System.out.println("The largest short value is " + largestShort);
        System.out.println("The largest integer value is " + largestInteger);
        System.out.println("The largest long value is " + largestLong);
        System.out.println("The largest float value is " + largestFloat);
        System.out.println("The largest double value is " + largestDouble);
        if (Character.isUpperCase(aChar)) {
            System.out.println("The character " + aChar + " is upper case.");
        } else {
            System.out.println("The character " + aChar + " is lower case.");
        }
        System.out.println("The value of aBoolean is " + aBoolean);
    }
}





Parse Number

    
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.NumberFormat;
import java.text.ParseException;
/**
 * Miscellaneous utility methods for number conversion and parsing.
 * Mainly for internal use within the framework; consider Jakarta"s
 * Commons Lang for a more comprehensive suite of string utilities.
 *
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @since 1.1.2
 */
public abstract class NumberUtils {
    /**
     * Convert the given number into an instance of the given target class.
     *
     * @param number      the number to convert
     * @param targetClass the target class to convert to
     * @return the converted number
     * @throws IllegalArgumentException if the target class is not supported
     *                                  (i.e. not a standard Number subclass as included in the JDK)
     * @see java.lang.Byte
     * @see java.lang.Short
     * @see java.lang.Integer
     * @see java.lang.Long
     * @see java.math.BigInteger
     * @see java.lang.Float
     * @see java.lang.Double
     * @see java.math.BigDecimal
     */
    public static Number convertNumberToTargetClass(Number number, Class targetClass)
            throws IllegalArgumentException {
        if (targetClass.isInstance(number)) {
            return number;
        } else if (targetClass.equals(Byte.class)) {
            long value = number.longValue();
            if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
                raiseOverflowException(number, targetClass);
            }
            return number.byteValue();
        } else if (targetClass.equals(Short.class)) {
            long value = number.longValue();
            if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
                raiseOverflowException(number, targetClass);
            }
            return number.shortValue();
        } else if (targetClass.equals(Integer.class)) {
            long value = number.longValue();
            if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
                raiseOverflowException(number, targetClass);
            }
            return number.intValue();
        } else if (targetClass.equals(Long.class)) {
            return number.longValue();
        } else if (targetClass.equals(Float.class)) {
            return number.floatValue();
        } else if (targetClass.equals(Double.class)) {
            return number.doubleValue();
        } else if (targetClass.equals(BigInteger.class)) {
            return BigInteger.valueOf(number.longValue());
        } else if (targetClass.equals(BigDecimal.class)) {
            // using BigDecimal(String) here, to avoid unpredictability of BigDecimal(double)
            // (see BigDecimal javadoc for details)
            return new BigDecimal(number.toString());
        } else {
            throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" +
                    number.getClass().getName() + "] to unknown target class [" + targetClass.getName() + "]");
        }
    }
    /**
     * Raise an overflow exception for the given number and target class.
     *
     * @param number      the number we tried to convert
     * @param targetClass the target class we tried to convert to
     */
    private static void raiseOverflowException(Number number, Class targetClass) {
        throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" +
                number.getClass().getName() + "] to target class [" + targetClass.getName() + "]: overflow");
    }
    /**
     * Parse the given text into a number instance of the given target class,
     * using the corresponding default <code>decode</code> methods. Trims the
     * input <code>String</code> before attempting to parse the number. Supports
     * numbers in hex format (with leading 0x) and in octal format (with leading 0).
     *
     * @param text        the text to convert
     * @param targetClass the target class to parse into
     * @return the parsed number
     * @throws IllegalArgumentException if the target class is not supported
     *                                  (i.e. not a standard Number subclass as included in the JDK)
     * @see java.lang.Byte#decode
     * @see java.lang.Short#decode
     * @see java.lang.Integer#decode
     * @see java.lang.Long#decode
     * @see #decodeBigInteger(String)
     * @see java.lang.Float#valueOf
     * @see java.lang.Double#valueOf
     * @see java.math.BigDecimal#BigDecimal(String)
     */
    public static Number parseNumber(String text, Class targetClass) {
        String trimmed = text.trim();
        if (targetClass.equals(Byte.class)) {
            return Byte.decode(trimmed);
        } else if (targetClass.equals(Short.class)) {
            return Short.decode(trimmed);
        } else if (targetClass.equals(Integer.class)) {
            return Integer.decode(trimmed);
        } else if (targetClass.equals(Long.class)) {
            return Long.decode(trimmed);
        } else if (targetClass.equals(BigInteger.class)) {
            return decodeBigInteger(trimmed);
        } else if (targetClass.equals(Float.class)) {
            return Float.valueOf(trimmed);
        } else if (targetClass.equals(Double.class)) {
            return Double.valueOf(trimmed);
        } else if (targetClass.equals(BigDecimal.class) || targetClass.equals(Number.class)) {
            return new BigDecimal(trimmed);
        } else {
            throw new IllegalArgumentException(
                    "Cannot convert String [" + text + "] to target class [" + targetClass.getName() + "]");
        }
    }
    /**
     * Parse the given text into a number instance of the given target class,
     * using the given NumberFormat. Trims the input <code>String</code>
     * before attempting to parse the number.
     *
     * @param text         the text to convert
     * @param targetClass  the target class to parse into
     * @param numberFormat the NumberFormat to use for parsing (if <code>null</code>,
     *                     this method falls back to <code>parseNumber(String, Class)</code>)
     * @return the parsed number
     * @throws IllegalArgumentException if the target class is not supported
     *                                  (i.e. not a standard Number subclass as included in the JDK)
     * @see java.text.NumberFormat#parse
     * @see #convertNumberToTargetClass
     * @see #parseNumber(String,Class)
     */
    public static Number parseNumber(String text, Class targetClass, NumberFormat numberFormat) {
        if (numberFormat != null) {
            try {
                Number number = numberFormat.parse(text.trim());
                return convertNumberToTargetClass(number, targetClass);
            }
            catch (ParseException ex) {
                throw new IllegalArgumentException(ex.getMessage());
            }
        } else {
            return parseNumber(text, targetClass);
        }
    }
    /**
     * Decode a {@link java.math.BigInteger} from a {@link String} value.
     * Supports decimal, hex and octal notation.
     *
     * @see BigInteger#BigInteger(String,int)
     */
    private static BigInteger decodeBigInteger(String value) {
        int radix = 10;
        int index = 0;
        boolean negative = false;
        // Handle minus sign, if present.
        if (value.startsWith("-")) {
            negative = true;
            index++;
        }
        // Handle radix specifier, if present.
        if (value.startsWith("0x", index) || value.startsWith("0X", index)) {
            index += 2;
            radix = 16;
        } else if (value.startsWith("#", index)) {
            index++;
            radix = 16;
        } else if (value.startsWith("0", index) && value.length() > 1 + index) {
      index++;
      radix = 8;
    }
    BigInteger result = new BigInteger(value.substring(index), radix);
    return (negative ? result.negate() : result);
  }
}





Primitive utilities

   
/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
/**
 * Primitive utilities.
 * 
 * @version <tt>$Revision: 1958 $</tt>
 * @author 
 */
public final class Primitives {
  /**
   * Get a Boolean from a boolean, equivalent to the java 1.4 method
   * Boolean.valueOf(boolean)
   * 
   * @param value
   *          the boolean
   * @return the Boolean equivalent
   */
  public static Boolean valueOf(boolean value) {
    if (value)
      return Boolean.TRUE;
    else
      return Boolean.FALSE;
  }
  /**
   * Test the equality of two doubles by converting their values into IEEE 754
   * floating-point "double format" long values.
   * 
   * @param a
   *          Double to check equality with.
   * @param b
   *          Double to check equality with.
   * @return True if a equals b.
   */
  public static boolean equals(final double a, final double b) {
    return Double.doubleToLongBits(a) == Double.doubleToLongBits(b);
  }
  /**
   * Test the equality of two doubles by converting their values into IEEE 754
   * floating-point "single precision" bit layouts.
   * 
   * @param a
   *          Float to check equality with.
   * @param b
   *          Float to check equality with.
   * @return True if a equals b.
   */
  public static boolean equals(final float a, final float b) {
    return Float.floatToIntBits(a) == Float.floatToIntBits(b);
  }
  /**
   * Test the equality of a given sub-section of two byte arrays.
   * 
   * @param a
   *          The first byte array.
   * @param abegin
   *          The begining index of the first byte array.
   * @param b
   *          The second byte array.
   * @param bbegin
   *          The begining index of the second byte array.
   * @param length
   *          The length of the sub-section.
   * @return True if sub-sections are equal.
   */
  public static boolean equals(final byte a[], final int abegin, final byte b[], final int bbegin,
      final int length) {
    try {
      int i = length;
      while (--i >= 0) {
        if (a[abegin + i] != b[bbegin + i]) {
          return false;
        }
      }
    } catch (ArrayIndexOutOfBoundsException e) {
      return false;
    }
    return true;
  }
  /**
   * Test the equality of two byte arrays.
   * 
   * @param a
   *          The first byte array.
   * @param b
   *          The second byte array.
   * @return True if the byte arrays are equal.
   */
  public static boolean equals(final byte a[], final byte b[]) {
    if (a == b)
      return true;
    if (a == null || b == null)
      return false;
    if (a.length != b.length)
      return false;
    try {
      for (int i = 0; i < a.length; i++) {
        if (a[i] != b[i]) {
          return false;
        }
      }
    } catch (ArrayIndexOutOfBoundsException e) {
      return false;
    }
    return true;
  }
}





Relational Demo

     
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
public class RelationalDemo {
  public static void main(String[] args) {
    //a few numbers
    int i = 37;
    int j = 42;
    int k = 42;
    System.out.println("Variable values...");
    System.out.println("    i = " + i);
    System.out.println("    j = " + j);
    System.out.println("    k = " + k);
    //greater than
    System.out.println("Greater than...");
    System.out.println("    i > j is " + (i > j)); //false
    System.out.println("    j > i is " + (j > i)); //true
    System.out.println("    k > j is " + (k > j)); //false, they are equal
    //greater than or equal to
    System.out.println("Greater than or equal to...");
    System.out.println("    i >= j is " + (i >= j)); //false
    System.out.println("    j >= i is " + (j >= i)); //true
    System.out.println("    k >= j is " + (k >= j)); //true
    //less than
    System.out.println("Less than...");
    System.out.println("    i < j is " + (i < j)); //true
    System.out.println("    j < i is " + (j < i)); //false
    System.out.println("    k < j is " + (k < j)); //false
    //less than or equal to
    System.out.println("Less than or equal to...");
    System.out.println("    i <= j is " + (i <= j)); //true
    System.out.println("    j <= i is " + (j <= i)); //false
    System.out.println("    k <= j is " + (k <= j)); //true
    //equal to
    System.out.println("Equal to...");
    System.out.println("    i == j is " + (i == j)); //false
    System.out.println("    k == j is " + (k == j)); //true
    //not equal to
    System.out.println("Not equal to...");
    System.out.println("    i != j is " + (i != j)); //true
    System.out.println("    k != j is " + (k != j)); //false
  }
}





Returns a default value if the object passed is null

  
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.io.Serializable;
/**
 * <p>Operations on <code>Object</code>.</p>
 * 
 * <p>This class tries to handle <code>null</code> input gracefully.
 * An exception will generally not be thrown for a <code>null</code> input.
 * Each method documents its behaviour in more detail.</p>
 *
 * @author 
 * @since 1.0
 * @version $Id: ObjectUtils.java 594336 2007-11-12 22:54:02Z bayard $
 */
public class ObjectUtils {
    /**
     * <p>Singleton used as a <code>null</code> placeholder where
     * <code>null</code> has another meaning.</p>
     *
     * <p>For example, in a <code>HashMap</code> the
     * {@link java.util.HashMap#get(java.lang.Object)} method returns
     * <code>null</code> if the <code>Map</code> contains
     * <code>null</code> or if there is no matching key. The
     * <code>Null</code> placeholder can be used to distinguish between
     * these two cases.</p>
     *
     * <p>Another example is <code>Hashtable</code>, where <code>null</code>
     * cannot be stored.</p>
     *
     * <p>This instance is Serializable.</p>
     */
    public static final Null NULL = new Null();
    
    /**
     * <p><code>ObjectUtils</code> instances should NOT be constructed in
     * standard programming. Instead, the class should be used as
     * <code>ObjectUtils.defaultIfNull("a","b");</code>.</p>
     *
     * <p>This constructor is public to permit tools that require a JavaBean instance
     * to operate.</p>
     */
    public ObjectUtils() {
        super();
    }
    // Defaulting
    //-----------------------------------------------------------------------
    /**
     * <p>Returns a default value if the object passed is
     * <code>null</code>.</p>
     * 
     * <pre>
     * ObjectUtils.defaultIfNull(null, null)      = null
     * ObjectUtils.defaultIfNull(null, "")        = ""
     * ObjectUtils.defaultIfNull(null, "zz")      = "zz"
     * ObjectUtils.defaultIfNull("abc", *)        = "abc"
     * ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
     * </pre>
     *
     * @param object  the <code>Object</code> to test, may be <code>null</code>
     * @param defaultValue  the default value to return, may be <code>null</code>
     * @return <code>object</code> if it is not <code>null</code>, defaultValue otherwise
     */
    public static Object defaultIfNull(Object object, Object defaultValue) {
        return object != null ? object : defaultValue;
    }
    /**
     * <p>Compares two objects for equality, where either one or both
     * objects may be <code>null</code>.</p>
     *
     * <pre>
     * ObjectUtils.equals(null, null)                  = true
     * ObjectUtils.equals(null, "")                    = false
     * ObjectUtils.equals("", null)                    = false
     * ObjectUtils.equals("", "")                      = true
     * ObjectUtils.equals(Boolean.TRUE, null)          = false
     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
     * </pre>
     *
     * @param object1  the first object, may be <code>null</code>
     * @param object2  the second object, may be <code>null</code>
     * @return <code>true</code> if the values of both objects are the same
     */
    public static boolean equals(Object object1, Object object2) {
        if (object1 == object2) {
            return true;
        }
        if ((object1 == null) || (object2 == null)) {
            return false;
        }
        return object1.equals(object2);
    }
    /**
     * <p>Gets the hash code of an object returning zero when the
     * object is <code>null</code>.</p>
     *
     * <pre>
     * ObjectUtils.hashCode(null)   = 0
     * ObjectUtils.hashCode(obj)    = obj.hashCode()
     * </pre>
     *
     * @param obj  the object to obtain the hash code of, may be <code>null</code>
     * @return the hash code of the object, or zero if null
     * @since 2.1
     */
    public static int hashCode(Object obj) {
        return (obj == null) ? 0 : obj.hashCode();
    }
    // Identity ToString
    //-----------------------------------------------------------------------
    /**
     * <p>Gets the toString that would be produced by <code>Object</code>
     * if a class did not override toString itself. <code>null</code>
     * will return <code>null</code>.</p>
     *
     * <pre>
     * ObjectUtils.identityToString(null)         = null
     * ObjectUtils.identityToString("")           = "java.lang.String@1e23"
     * ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
     * </pre>
     *
     * @param object  the object to create a toString for, may be
     *  <code>null</code>
     * @return the default toString text, or <code>null</code> if
     *  <code>null</code> passed in
     */
    public static String identityToString(Object object) {
        if (object == null) {
            return null;
        }
        StringBuffer buffer = new StringBuffer();
        identityToString(buffer, object);
        return buffer.toString();
    }
    /**
     * <p>Appends the toString that would be produced by <code>Object</code>
     * if a class did not override toString itself. <code>null</code>
     * will throw a NullPointerException for either of the two parameters. </p>
     *
     * <pre>
     * ObjectUtils.identityToString(buf, "")            = buf.append("java.lang.String@1e23"
     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa"
     * ObjectUtils.identityToString(buf, Boolean.TRUE)  = buf.append("java.lang.Boolean@7fa")
     * </pre>
     *
     * @param buffer  the buffer to append to
     * @param object  the object to create a toString for
     * @since 2.4
     */
    public static void identityToString(StringBuffer buffer, Object object) {
        if (object == null) {
            throw new NullPointerException("Cannot get the toString of a null identity");
        }
        buffer.append(object.getClass().getName())
              .append("@")
              .append(Integer.toHexString(System.identityHashCode(object)));
    }

    // ToString
    //-----------------------------------------------------------------------
    /**
     * <p>Gets the <code>toString</code> of an <code>Object</code> returning
     * an empty string ("") if <code>null</code> input.</p>
     * 
     * <pre>
     * ObjectUtils.toString(null)         = ""
     * ObjectUtils.toString("")           = ""
     * ObjectUtils.toString("bat")        = "bat"
     * ObjectUtils.toString(Boolean.TRUE) = "true"
     * </pre>
     * 
     * @see StringUtils#defaultString(String)
     * @see String#valueOf(Object)
     * @param obj  the Object to <code>toString</code>, may be null
     * @return the passed in Object"s toString, or nullStr if <code>null</code> input
     * @since 2.0
     */
    public static String toString(Object obj) {
        return obj == null ? "" : obj.toString();
    }
    /**
     * <p>Gets the <code>toString</code> of an <code>Object</code> returning
     * a specified text if <code>null</code> input.</p>
     * 
     * <pre>
     * ObjectUtils.toString(null, null)           = null
     * ObjectUtils.toString(null, "null")         = "null"
     * ObjectUtils.toString("", "null")           = ""
     * ObjectUtils.toString("bat", "null")        = "bat"
     * ObjectUtils.toString(Boolean.TRUE, "null") = "true"
     * </pre>
     * 
     * @see StringUtils#defaultString(String,String)
     * @see String#valueOf(Object)
     * @param obj  the Object to <code>toString</code>, may be null
     * @param nullStr  the String to return if <code>null</code> input, may be null
     * @return the passed in Object"s toString, or nullStr if <code>null</code> input
     * @since 2.0
     */
    public static String toString(Object obj, String nullStr) {
        return obj == null ? nullStr : obj.toString();
    }

    // Null
    //-----------------------------------------------------------------------
    /**
     * <p>Class used as a null placeholder where <code>null</code>
     * has another meaning.</p>
     *
     * <p>For example, in a <code>HashMap</code> the
     * {@link java.util.HashMap#get(java.lang.Object)} method returns
     * <code>null</code> if the <code>Map</code> contains
     * <code>null</code> or if there is no matching key. The
     * <code>Null</code> placeholder can be used to distinguish between
     * these two cases.</p>
     *
     * <p>Another example is <code>Hashtable</code>, where <code>null</code>
     * cannot be stored.</p>
     */
    public static class Null implements Serializable {
        /**
         * Required for serialization support. Declare serialization compatibility with Commons Lang 1.0
         * 
         * @see java.io.Serializable
         */
        private static final long serialVersionUID = 7092611880189329093L;
        
        /**
         * Restricted constructor - singleton.
         */
        Null() {
            super();
        }
        
        /**
         * <p>Ensure singleton.</p>
         * 
         * @return the singleton value
         */
        private Object readResolve() {
            return ObjectUtils.NULL;
        }
    }
}





Shows default initial values

     
// : c04:InitialValues.java
// Shows default initial values.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class InitialValues {
  boolean t;
  char c;
  byte b;
  short s;
  int i;
  long l;
  float f;
  double d;
  void print(String s) {
    System.out.println(s);
  }
  void printInitialValues() {
    print("Data type      Initial value");
    print("boolean        " + t);
    print("char           [" + c + "]");
    print("byte           " + b);
    print("short          " + s);
    print("int            " + i);
    print("long           " + l);
    print("float          " + f);
    print("double         " + d);
  }
  public static void main(String[] args) {
    InitialValues iv = new InitialValues();
    iv.printInitialValues();
    /*
     * You could also say: new InitialValues().printInitialValues();
     */
  }
} ///:~





Tests all the operators on all the primitive data types

     
//: c03:AllOps.java
// Tests all the operators on all the primitive data types
// to show which ones are accepted by the Java compiler.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
public class AllOps {
  // To accept the results of a boolean test:
  void f(boolean b) {}
  void boolTest(boolean x, boolean y) {
    // Arithmetic operators:
    //! x = x * y;
    //! x = x / y;
    //! x = x % y;
    //! x = x + y;
    //! x = x - y;
    //! x++;
    //! x--;
    //! x = +y;
    //! x = -y;
    // Relational and logical:
    //! f(x > y);
    //! f(x >= y);
    //! f(x < y);
    //! f(x <= y);
    f(x == y);
    f(x != y);
    f(!y);
    x = x && y;
    x = x || y;
    // Bitwise operators:
    //! x = ~y;
    x = x & y;
    x = x | y;
    x = x ^ y;
    //! x = x << 1;
    //! x = x >> 1;
    //! x = x >>> 1;
    // Compound assignment:
    //! x += y;
    //! x -= y;
    //! x *= y;
    //! x /= y;
    //! x %= y;
    //! x <<= 1;
    //! x >>= 1;
    //! x >>>= 1;
    x &= y;
    x ^= y;
    x |= y;
    // Casting:
    //! char c = (char)x;
    //! byte B = (byte)x;
    //! short s = (short)x;
    //! int i = (int)x;
    //! long l = (long)x;
    //! float f = (float)x;
    //! double d = (double)x;
  }
  void charTest(char x, char y) {
    // Arithmetic operators:
    x = (char)(x * y);
    x = (char)(x / y);
    x = (char)(x % y);
    x = (char)(x + y);
    x = (char)(x - y);
    x++;
    x--;
    x = (char)+y;
    x = (char)-y;
    // Relational and logical:
    f(x > y);
    f(x >= y);
    f(x < y);
    f(x <= y);
    f(x == y);
    f(x != y);
    //! f(!x);
    //! f(x && y);
    //! f(x || y);
    // Bitwise operators:
    x= (char)~y;
    x = (char)(x & y);
    x  = (char)(x | y);
    x = (char)(x ^ y);
    x = (char)(x << 1);
    x = (char)(x >> 1);
    x = (char)(x >>> 1);
    // Compound assignment:
    x += y;
    x -= y;
    x *= y;
    x /= y;
    x %= y;
    x <<= 1;
    x >>= 1;
    x >>>= 1;
    x &= y;
    x ^= y;
    x |= y;
    // Casting:
    //! boolean b = (boolean)x;
    byte B = (byte)x;
    short s = (short)x;
    int i = (int)x;
    long l = (long)x;
    float f = (float)x;
    double d = (double)x;
  }
  void byteTest(byte x, byte y) {
    // Arithmetic operators:
    x = (byte)(x* y);
    x = (byte)(x / y);
    x = (byte)(x % y);
    x = (byte)(x + y);
    x = (byte)(x - y);
    x++;
    x--;
    x = (byte)+ y;
    x = (byte)- y;
    // Relational and logical:
    f(x > y);
    f(x >= y);
    f(x < y);
    f(x <= y);
    f(x == y);
    f(x != y);
    //! f(!x);
    //! f(x && y);
    //! f(x || y);
    // Bitwise operators:
    x = (byte)~y;
    x = (byte)(x & y);
    x = (byte)(x | y);
    x = (byte)(x ^ y);
    x = (byte)(x << 1);
    x = (byte)(x >> 1);
    x = (byte)(x >>> 1);
    // Compound assignment:
    x += y;
    x -= y;
    x *= y;
    x /= y;
    x %= y;
    x <<= 1;
    x >>= 1;
    x >>>= 1;
    x &= y;
    x ^= y;
    x |= y;
    // Casting:
    //! boolean b = (boolean)x;
    char c = (char)x;
    short s = (short)x;
    int i = (int)x;
    long l = (long)x;
    float f = (float)x;
    double d = (double)x;
  }
  void shortTest(short x, short y) {
    // Arithmetic operators:
    x = (short)(x * y);
    x = (short)(x / y);
    x = (short)(x % y);
    x = (short)(x + y);
    x = (short)(x - y);
    x++;
    x--;
    x = (short)+y;
    x = (short)-y;
    // Relational and logical:
    f(x > y);
    f(x >= y);
    f(x < y);
    f(x <= y);
    f(x == y);
    f(x != y);
    //! f(!x);
    //! f(x && y);
    //! f(x || y);
    // Bitwise operators:
    x = (short)~y;
    x = (short)(x & y);
    x = (short)(x | y);
    x = (short)(x ^ y);
    x = (short)(x << 1);
    x = (short)(x >> 1);
    x = (short)(x >>> 1);
    // Compound assignment:
    x += y;
    x -= y;
    x *= y;
    x /= y;
    x %= y;
    x <<= 1;
    x >>= 1;
    x >>>= 1;
    x &= y;
    x ^= y;
    x |= y;
    // Casting:
    //! boolean b = (boolean)x;
    char c = (char)x;
    byte B = (byte)x;
    int i = (int)x;
    long l = (long)x;
    float f = (float)x;
    double d = (double)x;
  }
  void intTest(int x, int y) {
    // Arithmetic operators:
    x = x * y;
    x = x / y;
    x = x % y;
    x = x + y;
    x = x - y;
    x++;
    x--;
    x = +y;
    x = -y;
    // Relational and logical:
    f(x > y);
    f(x >= y);
    f(x < y);
    f(x <= y);
    f(x == y);
    f(x != y);
    //! f(!x);
    //! f(x && y);
    //! f(x || y);
    // Bitwise operators:
    x = ~y;
    x = x & y;
    x = x | y;
    x = x ^ y;
    x = x << 1;
    x = x >> 1;
    x = x >>> 1;
    // Compound assignment:
    x += y;
    x -= y;
    x *= y;
    x /= y;
    x %= y;
    x <<= 1;
    x >>= 1;
    x >>>= 1;
    x &= y;
    x ^= y;
    x |= y;
    // Casting:
    //! boolean b = (boolean)x;
    char c = (char)x;
    byte B = (byte)x;
    short s = (short)x;
    long l = (long)x;
    float f = (float)x;
    double d = (double)x;
  }
  void longTest(long x, long y) {
    // Arithmetic operators:
    x = x * y;
    x = x / y;
    x = x % y;
    x = x + y;
    x = x - y;
    x++;
    x--;
    x = +y;
    x = -y;
    // Relational and logical:
    f(x > y);
    f(x >= y);
    f(x < y);
    f(x <= y);
    f(x == y);
    f(x != y);
    //! f(!x);
    //! f(x && y);
    //! f(x || y);
    // Bitwise operators:
    x = ~y;
    x = x & y;
    x = x | y;
    x = x ^ y;
    x = x << 1;
    x = x >> 1;
    x = x >>> 1;
    // Compound assignment:
    x += y;
    x -= y;
    x *= y;
    x /= y;
    x %= y;
    x <<= 1;
    x >>= 1;
    x >>>= 1;
    x &= y;
    x ^= y;
    x |= y;
    // Casting:
    //! boolean b = (boolean)x;
    char c = (char)x;
    byte B = (byte)x;
    short s = (short)x;
    int i = (int)x;
    float f = (float)x;
    double d = (double)x;
  }
  void floatTest(float x, float y) {
    // Arithmetic operators:
    x = x * y;
    x = x / y;
    x = x % y;
    x = x + y;
    x = x - y;
    x++;
    x--;
    x = +y;
    x = -y;
    // Relational and logical:
    f(x > y);
    f(x >= y);
    f(x < y);
    f(x <= y);
    f(x == y);
    f(x != y);
    //! f(!x);
    //! f(x && y);
    //! f(x || y);
    // Bitwise operators:
    //! x = ~y;
    //! x = x & y;
    //! x = x | y;
    //! x = x ^ y;
    //! x = x << 1;
    //! x = x >> 1;
    //! x = x >>> 1;
    // Compound assignment:
    x += y;
    x -= y;
    x *= y;
    x /= y;
    x %= y;
    //! x <<= 1;
    //! x >>= 1;
    //! x >>>= 1;
    //! x &= y;
    //! x ^= y;
    //! x |= y;
    // Casting:
    //! boolean b = (boolean)x;
    char c = (char)x;
    byte B = (byte)x;
    short s = (short)x;
    int i = (int)x;
    long l = (long)x;
    double d = (double)x;
  }
  void doubleTest(double x, double y) {
    // Arithmetic operators:
    x = x * y;
    x = x / y;
    x = x % y;
    x = x + y;
    x = x - y;
    x++;
    x--;
    x = +y;
    x = -y;
    // Relational and logical:
    f(x > y);
    f(x >= y);
    f(x < y);
    f(x <= y);
    f(x == y);
    f(x != y);
    //! f(!x);
    //! f(x && y);
    //! f(x || y);
    // Bitwise operators:
    //! x = ~y;
    //! x = x & y;
    //! x = x | y;
    //! x = x ^ y;
    //! x = x << 1;
    //! x = x >> 1;
    //! x = x >>> 1;
    // Compound assignment:
    x += y;
    x -= y;
    x *= y;
    x /= y;
    x %= y;
    //! x <<= 1;
    //! x >>= 1;
    //! x >>>= 1;
    //! x &= y;
    //! x ^= y;
    //! x |= y;
    // Casting:
    //! boolean b = (boolean)x;
    char c = (char)x;
    byte B = (byte)x;
    short s = (short)x;
    int i = (int)x;
    long l = (long)x;
    float f = (float)x;
  }
} ///:~





Use Integer constructor to convert int primitive type to Integer object.

     
public class Main {
  public static void main(String[] args) {
    int i = 10;
    Integer intObj = new Integer(i);
    System.out.println(intObj);
  }
}