Showing posts with label udf. Show all posts
Showing posts with label udf. Show all posts

Wednesday, 22 June 2011

String utility : unquoting the string

This is another simple Java string utility method, which can be used to unquote a string value. This method takes care of single and double quotes both along with handling the null string. It returns the string as it is when the string is not quoted.

public static String unquote(String s) {
if (s != null && ((s.startsWith("\"") && s.endsWith("\""))
|| (s.startsWith("'") && s.endsWith("'")))) {

s = s.substring(1, s.length() - 1);
}
return s;
}

Wednesday, 2 February 2011

Finding the logarithm of any base in Java

Unfortunately, the only methods in Java that compute the logarithm of a number are java.lang.Math.log and java.lang.Math.log10. The former returns the natural logarithm (base e) of the number and the latter returns the base 10 logarithm of the number.

To calculate the logarithm of any base in Java, we thus have to use the following method:


  1. public double logOfBase(int base, int num) {  
  2.     return Math.log(num) / Math.log(base);  
  3. }  

Why does it work?


Let's say we want to find the base 2 logarithm of 32 (method call would be logOfBase(2, 32)), which is 5.


Now if we divide the base e logarithm (ln) of our number (32) by the base e logarithm of our base (2), we get the answer we wanted:

Wednesday, 22 December 2010

Getting java run time memory statistics

   public static void logJVMStatistics()
    {
        System.out.println("JVM Statistics -- Max : " + Runtime.getRuntime().maxMemory() + "; " +
                            "Free: " + Runtime.getRuntime().freeMemory() + "; " +
                            "Total: " + Runtime.getRuntime().totalMemory());
    }