Category Archives: Java.math

The Java Math Class

ejwagenaar.com logo

 

Introduction

Java.Math does exactly what it’s name implies. Mathematics. There’s something special is going on with the math class. It’s methods are all static. In other words they don’t have to be initialized. You can call them all in the static way, e.g. without the ‘new’ keyword. So to compute the sqare of a value we say:

Math.square(value);

Other examples of simple calculations:

Math.round(number to round);
Math.ceil(Number to Ceil);

Etcetera…..

Math also introduces special numbers like the BigDecimal.

// Create via a string
BigDecimal bd1 = new BigDecimal("123456789.0123456890");

// Create via a long
BigDecimal bd2 = BigDecimal.valueOf(123L);

bd1 = bd1.add(bd2);
bd1 = bd1.multiply(bd2);
bd1 = bd1.subtract(bd2);
bd1 = bd1.divide(bd2, BigDecimal.ROUND_UP);
bd1 = bd1.negate();

As you see the BigDecimal is an exception. It’s an encapsulated class, similar to Integer, Boolean or Char.

Some more examples:

// Create via a string
BigInteger bi1 = new BigInteger("1234567890123456890");

// Create via a long
BigInteger bi2 = BigInteger.valueOf(123L);

bi1 = bi1.add(bi2);
bi1 = bi1.multiply(bi2);
bi1 = bi1.subtract(bi2);
bi1 = bi1.divide(bi2);
bi1 = bi1.negate();
int exponent = 2;
bi1 = bi1.pow(exponent);
// Get a byte array
byte[] bytes = new byte[]{(byte)0x12, (byte)0x0F, (byte)0xF0};

// Create a BigInteger using the byte array
BigInteger bi = new BigInteger(bytes);

// Format to binary
String s = bi.toString(2);      // 100100000111111110000

// Format to octal
s = bi.toString(8);             // 4407760

// Format to decimal
s = bi.toString();              // 1183728

// Format to hexadecimal
s = bi.toString(16);            // 120ff0
if (s.length() % 2 != 0) {
    // Pad with 0
    s = "0"+s;
}


// Parse binary string
bi = new BigInteger("100100000111111110000", 2);

// Parse octal string
bi = new BigInteger("4407760", 8);

// Parse decimal string
bi = new BigInteger("1183728");

// Parse hexadecimal string
bi = new BigInteger("120ff0", 16);

// Get byte array
bytes = bi.toByteArray();