Monday 25 January 2016

BigDecimal in Java


A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale.
The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. The toString() method provides a canonical representation of a BigDecimal.

The BigDecimal class gives its user complete control over rounding behavior. If no rounding mode is specified and the exact result cannot be represented, an exception is thrown.

Difference between BigDecimal and Doubel:

  • Double is a wrapper for the Java native double type, that is a 64-bit floating point number.

BigDecimal is arbitrary-precision arithmetic. It can represent numbers to as many bits of precision as you want to throw memory and time at.

  • A Double has a certain precision. While a BigDecimal is an exact way of representing numbers. 


Disadvantage:
The disadvantage of BigDecimal is that it's slower, and it's a bit more difficult to program algorithms that way
(due to + - * and / not being overloaded).

Where to use what:
If you are dealing with money, or precision is a must, use BigDecimal. Otherwise Doubles enough to deal with.

Example:
BigDecimal bg1, bg2;
        bg1 = new BigDecimal("10");
        bg2 = new BigDecimal("20");

Class declaration
public class BigDecimal extends Number implements Comparable<BigDecimal>

Important Fields: 
Following are the fields for java.math.BigDecimal class:
1. static BigDecimal ONE -- The value 1, with a scale of 0.
2. static int ROUND_CEILING -- Rounding mode to round towards positive infinity.
3. static int ROUND_DOWN -- Rounding mode to round towards zero.
4. static int ROUND_FLOOR -- Rounding mode to round towards negative infinity.
5. static int ROUND_HALF_DOWN -- Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
6. static int ROUND_HALF_EVEN -- Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
7. static int ROUND_HALF_UP --Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
8. static int ROUND_UNNECESSARY --Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary.
9. static int ROUND_UP --Rounding mode to round away from zero.
10. static BigDecimal TEN --The value 10, with a scale of 0.
11. static BigDecimal ZERO --The value 0, with a scale of 0.

Class constructors and Description :
1 BigDecimal(BigInteger val) : Translates a BigInteger into a BigDecimal.

2 BigDecimal(BigInteger unscaledVal, int scale) : Translate a BigInteger unscaled value and an int scale into a BigDecimal.

3 BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) : Translate a BigInteger unscaled value and an int scale into a BigDecimal, with rounding according to the context settings.

4 BigDecimal(BigInteger val, MathContext mc) : Translate a BigInteger into a BigDecimal rounding according to the context settings.

5 BigDecimal(char[ ] in) : Translate a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the BigDecimal(String) constructor.

6 BigDecimal(char[ ] in, int offset, int len) : Translate a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the BigDecimal(String) constructor, while allowing a sub-array to be specified.

7 BigDecimal(char[ ] in, int offset, int len, MathContext mc) : Translate a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the BigDecimal(String) constructor, while allowing a sub-array to be specified and with rounding according to the context settings.

8 BigDecimal(char[ ] in, MathContext mc) : Translate a character array representation of a BigDecimal into a BigDecimal, accepting the same sequence of characters as the BigDecimal(String) constructor and with rounding according to the context settings.

9 BigDecimal(double val) : Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value.

10 BigDecimal(double val, MathContext mc) : Translates a double into a BigDecimal, with rounding according to the context settings.

11 BigDecimal(int val) : Translates an int into a BigDecimal.

12 BigDecimal(int val, MathContext mc) : Translates an int into a BigDecimal, with rounding according to the context settings.

13 BigDecimal(long val) : Translate a long into a BigDecimal.

14 BigDecimal(long val, MathContext mc) : Translates a BigInteger into a BigDecimal.

15 BigDecimal(String val) : Translates to the string representation of a BigDecimal into a BigDecimal.

16 BigDecimal(String val, MathContext mc) : Translates the string representation of a BigDecimal into a BigDecimal, accepting the same strings as the BigDecimal(String) constructor, with rounding according to the context settings.


Some important methods
1. BigDecimal add(BigDecimal augend)
This method returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()).
2. BigDecimal divide(BigDecimal divisor)
This method returns a BigDecimal whose value is (this / divisor), and whose preferred scale is (this.scale() - divisor.scale()); if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown.
3.double doubleValue()
This method converts the BigDecimal to a double.
4. boolean equals(Object x)
This method compares the BigDecimal with the specified Object for equality.
5. int hashCode()
This method returns the hash code for this BigDecimal.
6. int intValue()
This method converts the BigDecimal to an int.
7. long longValue()
This method converts the BigDecimal to a long.
8. BigDecimal max(BigDecimal val)
This method returns the maximum of this BigDecimal and val.
9. BigDecimal min(BigDecimal val)
This method returns the minimum of this BigDecimal and val.
10. BigDecimal multiply(BigDecimal multiplicand)
This method returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).
11. int scale()
This method returns the scale of this BigDecimal.
12. BigDecimal setScale(int newScale)
This method returns a BigDecimal whose scale is the specified value, and whose value is numerically equal to this BigDecimal's.

Examples:

import java.math.BigDecimal;
public class BigDecimalExamples {
    public static void main(String[] args) {
         // Create two new BigDecimals
        BigDecimal bigDecVal1 = null;
        BigDecimal bigDecVal2 = null;

        // Addition of two BigDecimals
        bigDecVal1 = new BigDecimal("521");
        bigDecVal2 = new BigDecimal("325");
        bigDecVal1 = bigDecVal1.add(bigDecVal2);
        System.out.println("bigDecVal1 = " + bigDecVal1);

        // Multiplication of two BigDecimals
        bigDecVal1 = new BigDecimal("5211");
        bigDecVal2 = new BigDecimal("3251");
        bigDecVal1 = bigDecVal1.multiply(bigDecVal2);
        System.out.println("bigDecVal1 = " + bigDecVal1);

        // Subtraction of two BigDecimals
        bigDecVal1 = new BigDecimal("5212");
        bigDecVal2 = new BigDecimal("3252");
        bigDecVal1 = bigDecVal2.subtract(bigDecVal1);
        System.out.println("bigDecVal1 = " + bigDecVal1);

        // Division of two BigDecimals
        bigDecVal1 = new BigDecimal("5");
        bigDecVal2 = new BigDecimal("12");
        BigDecimal result = bigDecVal2.divide(bigDecVal1);
        System.out.println("bigDecVal1 = " + result);

        // BigDecima1 raised to the power of 2
        bigDecVal1 = new BigDecimal("5214");
        bigDecVal2 = new BigDecimal("3254");
        bigDecVal1 = bigDecVal1.pow(2);
        System.out.println("bigDecVal1 = " + bigDecVal1);

        // Negate value of BigDecimal1
        bigDecVal1 = new BigDecimal("5215");
        bigDecVal2 = new BigDecimal("3255");
        bigDecVal1 = bigDecVal1.negate();
        System.out.println("bigDecVal1 = " + bigDecVal1);

// Using Rounding mode
BigDecimal bdScale = new BigDecimal(50.555);
bdScale.setScale(2, RoundingMode.CEILING);
System.out.println("bdScale = " + bdScale);
    }
}

Outoput
bigDecVal1 = 846
bigDecVal1 = 16940961
bigDecVal1 = -1960
bigDecVal1 = 2.4
bigDecVal1 = 27185796
bigDecVal1 = -5215
bdScale = 50.55499999999999971578290569595992565155029296875

Here we got 50.55499999999999971578290569595992565155029296875 of decimal value 50.555 that is called loss of precision
Get exact precision of double value
double doubleVal = 50.55;
BigDecimal bigDecimalVal = new BigDecimal(String.valueOf(doubleVal));

Output will be 50.555

Thursday 21 January 2016

Java memory structure

1. Java Heap Size:
Heap memory area is used to store objects created by your Java application and Garbage Collection uses this to free memory area used by Java Objects that are not in used.
For a heavy Java process, insufficient Heap size will cause java.lang.OutOfMemoryError Java heap space exception.

Command to increase Heap Size
-Xms<size> - Set initial Java heap size
-Xmx<size> - Set maximum Java heap size

$ java -Xms512m -Xmx1024m AppName


2. Perm Gen Size
Perm Gen memory area is used to store class definition and metadata of loaded classes. If a large code base project is loaded, the insufficient Perm Gen Size will cause the Java.Lang.OutOfMemoryError: PermGen exception.

Command to increate Perm Gen Size
-XX:PermSize=<Size> - Set initial perm size
-XX:MaxPerSize=<size>  - Set Maximum Per Size
Example:
$ java -XX:PermSize=64m -XX:MaxPermSize=128m AppName


3. Java Stack Size
Stack Size memory area is used to define the size of thread. If any application have many thread it recomended to reduce the stack size to avoid Java.Lang.OutOfMemoryError exception

Command to increase Stack Size
-Xss<size> - Set Java thread stack size
Example:
-Xss512k