Java

Java programming language

Installation of JDK

JDK is the software development kit for creating Java programs. Instructions below show you step-by-step how to install and set it up.

  1. Download JDK. Install it and follow the instructions shown on the screen.
  2. Now that the JDK is installed, you have to add the binary folder path of the JDK to the PATH environment variable of your MS Windows.
    1. Depending on the version of your MS Windows, the steps below may be different but similar.
      • If you are using MS Windows XP, then open [Classic View]Control Panel->System->Advanced->Environment Variables.
      • If you are using MS Windows Vista, then open [Classic View] Control Panel->System->Advanced system settings->Advanced->Environment Variables.
    2. Under the User variables for X(e.g. Administrator) section, search for the PATH variable. If the PATH variable is not listed, then create it. Otherwise, edit it.
    3. If you have to edit the PATH, then select it. Click on the Edit button and append the following line to the Variable value input field:
      ;C:\Program Files\Java\jdk1.6.0_06\bin
       
      Note: There is a semicolon(;) in front and the path may be different in your case depending on the location where you did install your JDK or the version number of your JDK. The semicolon(;) is used to separated multiple paths.
    4. If you have to create the PATH, then click on the New button. Set the Variable name to PATH and then set the Variable value to
      C:\Program Files\Java\jdk1.6.0_06\bin
       
      Note: The path may be different in your case depending on the location where you did install your JDK or the version number of your JDK. The semicolon(;) is used to separated multiple paths.
    5. Click on the OK buttons.
    6. Open a new Command Prompt for the change to take effect and then execute the following command:
      javac -version
       
      It should show the version number of your Java Compiler(javac).

Setting the class path

This tutorial offers step-by-step instructions on how to set up the class path. I will use selenium-java-client-driver.jar and junit-4.5.jar as examples to show you how to add them to the CLASSPATH.

  1. Depending on the version of your MS Windows, the steps below may be different but similar.
    • If you are using MS Windows XP, then open [Classic View]Control Panel->System->Advanced->Environment Variables.
    • If you are using MS Windows Vista, then open [Classic View] Control Panel->System->Advanced system settings->Advanced->Environment Variables.
  2. Under the User variables for X(e.g. Administrator) section, search for the CLASSPATH variable. If the CLASSPATH variable is not listed, then create it. Otherwise, edit it.
  3. If you have to edit it, then select it. Click on the Edit button and append the following line to the Variable value input field:
    ;C:\selenium-java-client-driver.jar
     
    Note: There is a semicolon(;) in front and the path may be different in your case depending on the location of your selenium-java-client-driver.jar file. The semicolon(;) is used to separated multiple paths. For example, if you want to also add JUnit's jar file to the CLASSPATH, you have to append the following line to the Variable value input field:
    ;C:\selenium-java-client-driver.jar;C:\junit-4.5.jar
     
  4. If you have to create it, then click on the New button. Set the Variable name to CLASSPATH and then set the Variable value to
    C:\selenium-java-client-driver.jar
     
    Note: To add multiple paths, use the semicolon(;) as separator. For example, if you want to also add JUnit's jar file to the CLASSPATH, then set the Variable value input field to
    C:\selenium-java-client-driver.jar;C:\junit-4.5.jar  
     
  5. Click on the OK buttons.
  6. Open a new Command Prompt for the change to take effect and then execute the following command:
    echo %CLASSPATH%
     
    It should return the paths of your jar files(i.e. paths of selenium-java-client-driver.jar and junit-4.5.jar).

Append text to file

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
 
/**
 * Append text to file.
 * @author Xuan Ngo
 */
public class AppendTextToFile
{
  public static void main(String[] args)
  {
 
    try
    {
      final String filename="file.txt";
 
      // FileWriter(File file, boolean append): Set append boolean to true to append text.
      PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)));
      writer.println("Some text to append");
      writer.close();
    }
    catch(IOException e)
    {
      e.printStackTrace();
    }
  }
 
}

Boundaries of primitive data types in Java

The code

/**
 * Show the boundaries of primitive data types in Java.
 * Note: Unlike other languages(e.g. C/C++), Java doesn't provide unsigned types of its integers.
 * @author Xuan Ngo
 *
 */
public class BoundariesOfPrimitiveDataTypes
{
  public static void main(String[] args)
  {
    String s = "";
 
    // Byte
    s = String.format("%-24s: min = %,-27d, max = %,-27d", Byte.class, Byte.MIN_VALUE, Byte.MAX_VALUE);
    System.out.println(s);
 
    // Short
    s = String.format("%-24s: min = %,-27d, max = %,-27d", Short.class, Short.MIN_VALUE, Short.MAX_VALUE);
    System.out.println(s);
 
    // Integer
    s = String.format("%-24s: min = %,-27d, max = %,-27d", Integer.class, Integer.MIN_VALUE, Integer.MAX_VALUE);
    System.out.println(s);
 
    // Long
    s = String.format("%-24s: min = %,-27d, max = %,-27d", Long.class, Long.MIN_VALUE, Long.MAX_VALUE);
    System.out.println(s);
 
    // Float
    s = String.format("%-24s: min = %-27s, max = %,f", Float.class, Float.MIN_VALUE, Float.MAX_VALUE);
    System.out.println(s);
 
    // Double
    s = String.format("%-24s: min = %-27s, max = %s", Double.class, Double.MIN_VALUE, Double.MAX_VALUE);
    System.out.println(s);
 
    // Boolean
    s = String.format("%-24s: min = %-27b, max = %b", Boolean.class, Boolean.FALSE, Boolean.TRUE);
    System.out.println(s);
 
  }
}

The output

class java.lang.Byte    : min = -128                       , max = 127                        
class java.lang.Short   : min = -32,768                    , max = 32,767                     
class java.lang.Integer : min = -2,147,483,648             , max = 2,147,483,647              
class java.lang.Long    : min = -9,223,372,036,854,775,808 , max = 9,223,372,036,854,775,807  
class java.lang.Float   : min = 1.4E-45                    , max = 340,282,346,638,528,860,000,000,000,000,000,000,000.000000
class java.lang.Double  : min = 4.9E-324                   , max = 1.7976931348623157E308
class java.lang.Boolean : min = false                      , max = true

Capture and store console output(System.out.println())

/**
 * How to capture and store console output(System.out.println()).
 * @author Xuan Ngo
 */
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
 
public class ConsoleTutorial
{
 
  public static void main(String[] args)
  {
    System.out.println("One");
 
    // Storing console output to consoleStorage.
    ByteArrayOutputStream consoleStorage = new ByteArrayOutputStream();
    PrintStream newConsole = System.out;
    System.setOut(new PrintStream(consoleStorage));
 
    // Here all System.out.println() calls will be stored in consoleStorage.
    System.out.println("two");     // Note: The output "two" you see from the console 
                                //        doesn't come from this line but from the lines below(newConsole.println());
 
    newConsole.println(consoleStorage.toString());
    newConsole.println(consoleStorage.toString());
 
    // Restore back the standard console output.
    System.setOut(newConsole);
 
    // Print to console.
    System.out.println("three");
    System.out.println(consoleStorage.toString());
  }
}

Convert a list into an array of a specific class

/**
 * Show how to convert a list into an array of specific class using toArray().
 */
import java.util.ArrayList;
 
public class ToArrayInSpecificClassType
{
  public static void main(String[] args)
  {
    // Create sample data.
    ArrayList<String> lStrings = new ArrayList<String>();
    lStrings.add("ab"); lStrings.add("cd"); lStrings.add("ef");
 
    // This will return an array of object. It isn't what we want.
    Object[] oStrings = lStrings.toArray();
 
    // This will return an array of specific class type(i.e String).
    String[] aStrings = lStrings.toArray(new String[0]);
 
  }
 
}

Convert an octal value to its corresponding ASCII value

/**
 * Convert an octal value to its corresponding ASCII value.
 * Convert from octal(base 8)->decimal(base 10)->character.
 * @author Xuan Ngo
 */
public class OctalToAscii
{
  public static void main(String[] args)
  {
    // Note: octal is base 8.
    String sOctal = "355";
 
    // Convert Octal(base8) to decimal(base 10).
    Integer iOctal = Integer.parseInt(sOctal, 8);
    System.out.println(iOctal); // Output: 237
 
    // Cast decimal to its corresponding ASCII value.
    char cOctal = (char)iOctal.intValue();
    System.out.println(cOctal); // Output í
  }
 
}

Find a linear function that represents a set of data points

To find a linear function(a straight line) that represents a set of data points, you have to implement Simple Linear Regression. Here is an example.

/**
 * Simple Linear Regression: Find a linear function that represents a set of data points.
 * @author Xuan Ngo 
 */
import java.util.ArrayList;
import static java.lang.Math.pow;
import java.lang.RuntimeException;
 
public class SimpleLinearRegression
{
  private ArrayList<Double> m_aX = new ArrayList<Double>();
  private ArrayList<Double> m_aY = new ArrayList<Double>();
 
  private ArrayList<Double> m_aXX = null;
  private ArrayList<Double> m_aXY = null;
 
  private double m_dSumOfXs = 0;
  private double m_dSumOfYs = 0;
  private double m_dSumOfXXs = 0;
  private double m_dSumOfXYs = 0;
 
  private double m_dSlope = 0;
 
  public static void main(String[] args)
  {
    ArrayList<Double> aX = new ArrayList<Double>();
    aX.add(new Double(60));
    aX.add(new Double(61));
    aX.add(new Double(62));
    aX.add(new Double(63));
    aX.add(new Double(65));
    ArrayList<Double> aY = new ArrayList<Double>();
    aY.add(new Double(3.1));
    aY.add(new Double(3.6));
    aY.add(new Double(3.8));
    aY.add(new Double(4));
    aY.add(new Double(4.1));
 
    /* // Bad case
    ArrayList<Double> aX = new ArrayList<Double>();
    aX.add(new Double(1));
    aX.add(new Double(4));
    aX.add(new Double(6));
    aX.add(new Double(13));
    aX.add(new Double(6));
    ArrayList<Double> aY = new ArrayList<Double>();
    aY.add(new Double(3));
    aY.add(new Double(1));
    aY.add(new Double(2));
    aY.add(new Double(6));
    aY.add(new Double(9));
    */
 
    SimpleLinearRegression slr = new SimpleLinearRegression(aX, aY);
 
    System.out.println("Slope = "+slr.getSlope()+"  Intercept = "+slr.getIntercept());
    System.out.println("y = "+slr.getSlope()+"x + ("+slr.getIntercept()+")");
 
  }
  public SimpleLinearRegression(final ArrayList<Double> aX, final ArrayList<Double> aY)
  {
    this.m_aX = aX;
    this.m_aY = aY;
 
    // Prepare sigma values.
    this.m_dSumOfXs = this.sum(aX);
    this.m_dSumOfYs = this.sum(aY);
 
    this.calculateXX();
    this.m_dSumOfXXs = this.sum(this.m_aXX);
 
    this.calculateXY();
    this.m_dSumOfXYs = this.sum(this.m_aXY);
  }
 
  /**
   * Slope = (NΣXY - (ΣX)(ΣY)) / (NΣ(X^2) - (ΣX)^2)
   * where, N = number of values.
   * @return
   */
  public double getSlope()
  {
    final int iNumOfValues = this.m_aX.size();
    final double dSlope = ((iNumOfValues*this.m_dSumOfXYs) - (this.m_dSumOfXs*this.m_dSumOfYs)) / ((iNumOfValues*this.m_dSumOfXXs) - pow(this.m_dSumOfXs, 2.0));
 
    this.m_dSlope = dSlope; 
    return this.m_dSlope;
  }
  /**
   * Intercept = (ΣY - b(ΣX)) / N 
   * where, N = number of values.
   * @return
   */
  public double getIntercept()
  {
    // If slope is 0 throw an exception.
    if(this.m_dSlope==0)
      throw new RuntimeException("Run this.getSlope() to calculate the slope first.");
 
    final int iNumOfValues = this.m_aX.size();
    final double dConstant = (this.m_dSumOfYs - (this.m_dSlope*this.m_dSumOfXs)) / iNumOfValues;
 
    return dConstant;
  }
  /**
   * Sum all values in the array list.
   * @param aD
   * @return
   */
  private double sum(ArrayList<Double> aD)
  {
    double dSum=0;
    for(int i=0; i<aD.size(); i++)
    {
      dSum+=aD.get(i).doubleValue();
    }
    return dSum;
  }
 
  /**
   * Calculate X*Y for all values.
   */
  private void calculateXY()
  {
    this.m_aXY = new ArrayList<Double>();
 
    for(int i=0; i<this.m_aX.size(); i++)
    {
      double x = this.m_aX.get(i).doubleValue();
      double y = this.m_aY.get(i).doubleValue();
 
      this.m_aXY.add(new Double(x*y));
    }
  }
  /**
   * Calculate X*X for all values.
   */
  private void calculateXX()
  {
    this.m_aXX = new ArrayList<Double>();
 
    for(int i=0; i<this.m_aX.size(); i++)
    {
      double x = this.m_aX.get(i).doubleValue();
      this.m_aXX.add(new Double(x*x));
    }    
  }
}
/**
 * Test cases of SimpleLinearRegression class
 * @author Xuan Ngo
 */
import java.util.ArrayList;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
 
public class SimpleLinearRegressionTest
{
  @Test
  public void slrPositiveSlopeTest()
  {
    ArrayList<Double> aX = new ArrayList<Double>();
    ArrayList<Double> aY = new ArrayList<Double>();
    aX.add(new Double(0.0));  aY.add(new Double(4.0));
    aX.add(new Double(3.0));  aY.add(new Double(8.0));
 
    SimpleLinearRegression slr = new SimpleLinearRegression(aX, aY);
 
    assertEquals(slr.getSlope(), (8.0-4.0)/(3.0-0.0));
    assertEquals(slr.getIntercept(), 4.0);
  }
 
  @Test
  public void slrNegativeSlopeTest()
  {
    ArrayList<Double> aX = new ArrayList<Double>();
    ArrayList<Double> aY = new ArrayList<Double>();
    aX.add(new Double(0.0));  aY.add(new Double(8.0));
    aX.add(new Double(3.0));  aY.add(new Double(4.0));
 
    SimpleLinearRegression slr = new SimpleLinearRegression(aX, aY);
 
    assertEquals(slr.getSlope(), (4.0-8.0)/(3.0-0.0));
    assertEquals(slr.getIntercept(), 8.0);
  }  
}

Reference: http://www.easycalculation.com/statistics/learn-regression.php

Try: http://commons.apache.org/proper/commons-math/userguide/stat.html#a1.4_Simple_regression

Find the degree of a slope

/**
 * Show how to find the degree of a slope.
 * @author Xuan Ngo
 */
public class Trigonometry
{
 
  public static void main(String[] args)
  {
    /**
     * All trigonometric functions in java.lang.Math return values in radians.
     * Therefore, you can use the Math.toDegrees() to convert to degree.
     * The inverse of sin, cosine and tangent are arcsine, arccosine and arctangent.
     */
    double dSlope = 1; // Let the slope be 1: (0,0), (1,1)
    double dRadian = Math.atan(dSlope);
    double dDegree = Math.toDegrees(dRadian);
 
    System.out.println(dDegree); // The expected output is: 45 degrees.
  }
 
}

Get a list of holiday dates using Jollyday library

/**
 * Show how to get a list of holiday dates using Jollyday(jollyday-0.4.3.jar) and Joda-Time(joda-time-1.6.2.jar).
 * You need Joda-Time library => http://joda-time.sourceforge.net/.
 * You need Jollyday library => http://jollyday.sourceforge.net/.
 */
import de.jollyday.HolidayCalendar;
import de.jollyday.HolidayManager;
import de.jollyday.Holiday;
import java.util.Collections;
 
import java.util.Set;
import java.util.ArrayList;
 
public class Jollyday
{
 
  public static void main(String[] args)
  {
    Jollyday oTest = new Jollyday();
 
    // Print out all holiday dates of each year.
    for(int i=2008; i<=2011; i++)
    {
      ArrayList<String> lHolidays = oTest.getHolidays(i);
      for(String sHoliday: lHolidays)
      {
        System.out.print(sHoliday+" | ");
      }
      System.out.println();
    }
 
  }
 
  /**
   * Get a list of holiday dates of a given year.
   * @param iYear
   * @return List of holiday dates of the whole year.
   */
  public ArrayList<String> getHolidays(int iYear)
  {
    ArrayList<String> oSortedHolidays = new ArrayList<String>();
    try
    {
      HolidayManager oManager = HolidayManager.getInstance(HolidayCalendar.CANADA);
 
      Set<Holiday> oHolidays = oManager.getHolidays(iYear, "qc"); // Quebec province
      for(Holiday oHoliday: oHolidays)
      {
        oSortedHolidays.add(oHoliday.toString());
      }
 
      // Sorted holiday dates.
      Collections.sort(oSortedHolidays);
    }
    catch(Exception ex)
    {
      System.out.println(ex.getMessage());
    }
 
    return oSortedHolidays;
  }
 
}

How to create and read properties file

import java.util.Properties;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
/**
 * Show how to create and read properties file.
 * @author Xuan Ngo
 */
public class MyProperties
{
  public static void main(String args[])
  {
    /**
     * Create and save the properties into a file.
     */
 
    // Create the properties object and add some values.
    Properties oWriteProperties = new Properties();
    oWriteProperties.setProperty("key1", "value1");
    oWriteProperties.setProperty("key2", "value2");
    oWriteProperties.setProperty("chinese", "中文");
 
    // Save properties into file. 
    try
    {
      oWriteProperties.store(new FileOutputStream("myproperties.properties"), "my first properties list");
    }
    catch(FileNotFoundException ex)
    {
      System.out.println(ex.getMessage());
    }
    catch(IOException ex)
    {
      System.out.println(ex.getMessage());
    }
 
    /**
     * Read properties file created.
     */
    Properties oReadProperties = new Properties();
    try
    {
      oReadProperties.load(new FileInputStream("myproperties.properties"));
    }
    catch(FileNotFoundException ex)
    {
      System.out.println(ex.getMessage());
    }
    catch(IOException ex)
    {
      System.out.println(ex.getMessage());
    }
 
    System.out.println(oReadProperties.getProperty("key2"));
    System.out.println(oReadProperties.getProperty("chinese"));
  }
}

Input Redirection

/**
 * Example showing how to read from input redirection. 
 * It accepts input from user or from file(i.e < someTextFile.txt).
 * @author Xuan Ngo
 */
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
 
public class InputRedirection
{
 
  public static void main(String[] args)
  {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String line = null;
 
    try
    {
      while( (line = reader.readLine()) != null )
      {
        if(line.length()==0)// Quit if user presses Enter. 
          System.exit(0);
 
        System.out.println(line);
      }
    }
    catch(IOException ex)
    {
      ex.printStackTrace();
    }
  }
 
}

Javadoc example

package org.javadoc.tutorial;
 
import java.lang.String;
 
/**
 * Example of what can be done with javadoc.
 * 
 * This is a longer description that can span into
 * multiple lines.
 * 
 * <ul>
 *  <li>{@literal {@value package.class#variable}} shows the value of a public variable 
 *        but it can't show a private variable.
 *  <li>{@literal {@link package.class#variableOrMethod}} links to the variable or method 
 *        but it can't link a private variable or method.
 * </ul>
 * 
 * @author Xuan Ngo
 * @version 1.0
 */
public class Person
{
  /** The person is a novice in the field. */
  public static final int NOVICE = 0;
 
  /** The person is an expert in the field. */
  public static final int EXPERT = 1;
 
  /** If a person has more than 10 years of experience, then that person is an expert. */
  private final int m_iExpertYearsOfExperience = 10;
 
  private String m_sFirstname = "";
  private String m_sLastname = "";
  private int m_iExpertise = 0; // By default, the person is a novice.
 
  /**
   * This is the constructor.
   */
  public Person()
  {
  }
 
  /**
   * Set the names.
   * @param sFirstname  The first name.
   * @param sLastname   The last name.
   */
  public void setNames(final String sFirstname, final String sLastname)
  {
    this.m_sFirstname = sFirstname;
    this.m_sLastname = sLastname;
  }
 
  /**
   * Get the names of the person.
   * @deprecated Don't use this function. It is not flexible. 
   * Use {@link #getFirstname()} and {@link org.javadoc.tutorial.Person#getLastname() Text linked to getLastname()} instead. 
   * @return Get the names of the person.
   */
  public final String getNames()
  {
    return this.m_sFirstname + " " + this.m_sLastname;
  }
 
  /**
   * Set the number of years of experience.
   * @param iYearsOfExperience Number of years of experience.
   */
  public void setYearsOfExperience(final int iYearsOfExperience)
  {
    if(iYearsOfExperience>this.m_iExpertYearsOfExperience)
    {
      this.m_iExpertise = EXPERT;
    }
    else
    {
      this.m_iExpertise = NOVICE;      
    }
  }
 
  /**
   * Get the level of expertise of this person.
   * @return {@value #EXPERT} if the person is an expert. Otherwise, {@value #NOVICE}.
   */
  public final int getExpertise()
  {
    return this.m_iExpertise;
  }
 
  /**
   * Get the first name
   * @return Get the first name
   */
  public final String getFirstname()
  {
    return this.m_sFirstname;
  }
 
  /**
   * Get the last name.
   * @return Get the last name.
   */
  public final String getLastname()
  {
    return this.m_sLastname;
  }
 
}

List files from a directory

/**
 * List files from a directory.
 * @author Xuan Ngo
 */
import java.io.File;
 
public class ListFilesFromDirectory
{
  public static void main(String[] args)
  {
    String sDirectoryPath = "mydirectorypath";
    File oDirectory = new File(sDirectoryPath);
    if(oDirectory.isDirectory())
    {
      File[] aFiles = oDirectory.listFiles();
      for(int i=0; i<aFiles.length; i++)
      {
        System.out.println(aFiles[i].getPath());
      }
    }
    else
    {
      System.out.println(sDirectoryPath+" is not a directory.");
    }
  }
 
}

Mapping of Java and MySQL data types

MySQL Data Type Java Data Type
CHAR String
VARCHAR String
LONGVARCHAR String
NUMERIC java.math.BigDecimal
DECIMAL java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE double
BINARY byte []
VARBINARY byte []
LONGVARBINARY byte []
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Tiimestamp

More details at: http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-type-conversions.html

Measure time elapsed

package net.xngo.utils.java.time;
 
/**
 * Measure time elapsed.
 * @author Xuan Ngo
 *
 */
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
 
public class ElapsedTime 
{
  private Calendar startTime = null;
  private Calendar endTime   = null;
 
 
  public ElapsedTime(){}
 
  public void start()
  {
    this.startTime = Calendar.getInstance();
  }
 
  public void setStart(final Calendar calendar)
  {
    this.startTime = calendar;
  }
 
  public void stop()
  {
    this.endTime = Calendar.getInstance();
  }
 
  public void setStop(final Calendar calendar)
  {
    this.endTime = calendar;
  }
 
  /**
   * @return Return the elapsed time measured in milliseconds.
   */
  public final long getDiffInMillis()
  {
    return this.endTime.getTimeInMillis() - this.startTime.getTimeInMillis();
  }
 
  /**
   * @return Return the elapsed time measured as HH:MM:SS.mmmm.
   */
  public final String getDiffInString()
  {
 
    long lTotalRuntime = this.getDiffInMillis();
    long lRuntime      = lTotalRuntime;
 
    // Calculate hours, minutes and seconds.     
    long lRuntimeHrs = lRuntime/(1000*3600);
    lRuntime         = lRuntime - (lRuntimeHrs*1000*3600);// Runtime remaining.
    long lRuntimeMin = (lRuntime)/(1000*60);
    lRuntime         = lRuntime - (lRuntimeMin*1000*60);  // Runtime remaining.
    long lRuntimeSec = lRuntime/(1000);
    lRuntime         = lRuntime - (lRuntimeSec*1000);     // Runtime remaining.
 
    return String.format("%02d", lRuntimeHrs)+":"+String.format("%02d", lRuntimeMin)+":"+String.format("%02d", lRuntimeSec)+"."+lRuntime;
  }
 
  public void display()
  {
    // Start at YYYY-MM-DD HH:MM:SS.mmm
    System.out.println(String.format("Start at %s", this.getDateTimeFormatted(this.startTime)));
 
    // End at YYYY-MM-DD HH:MM:SS.mmm
    System.out.println(String.format("End   at %s", this.getDateTimeFormatted(this.endTime)));
 
    // Ran for HH:MM:SS.mmm (milliseconds)
    System.out.println(String.format("Ran  for %s", this.getDiffInString()));
 
  }
 
  private final String getDateTimeFormatted(Calendar oCalendar)
  {
    final String dateFormat = "yyyy-MM-dd HH:mm:ss.SSSS";
 
    Date currentDate = oCalendar.getTime();
    SimpleDateFormat oSimpleDateFormat = new SimpleDateFormat(dateFormat);
    return oSimpleDateFormat.format(currentDate);
  }
}

https://github.com/xuanngo/Java/blob/master/Java/src/net/xngo/utils/java/time/ElapsedTime.java

Read and write Excel file using Apache POI

/**
 * Example showing how to read and write Excel file(i.e *.xls or *.xlsx).
 * JAR files needed:
 *  poi-3.6-20091214.jar
 *  poi-ooxml-3.6-20091214.jar
 * If you only need to handle Excel 2007 OOXML (.xlsx) file format, then you can use XSSF* classes.
 * If you only need to handle Excel 97-2003(.xls) file format, then you can use HSSF* classes.
 * @author Xuan Ngo
 */
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.WorkbookFactory; // This is included in poi-ooxml-3.6-20091214.jar
import org.apache.poi.ss.usermodel.Workbook;
 
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
 
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 
public class PoiExample
{
 
  public static void main(String[] args)
  {
    try
    {
 
      //***********************************
      // Read an Excel file.
      //***********************************
 
      // WorkbookFactory create the appropriate kind of Workbook (be it HSSFWorkbook or XSSFWorkbook), by auto-detecting from the supplied input.
      Workbook readWorkbook = WorkbookFactory.create(new FileInputStream("my_original_excel.xls") );
 
      // Get the first sheet.
      Sheet sheet = readWorkbook.getSheetAt(0);
 
      // Get the first cell.
      Row row = sheet.getRow(0);
      Cell cell = row.getCell(0);
 
      // Show what is being read.
      System.out.println(cell.toString());
 
 
      //***********************************
      // Create an Excel file.
      //***********************************
      Workbook writeWorkbook = new HSSFWorkbook();
      Sheet sheet1 = writeWorkbook.createSheet("new sheet");
 
      Row row1 = sheet1.createRow(0);
      Cell cell1 = row1.createCell(0);
      cell1.setCellValue("Xuan");
 
      // Write workbook to a file.
      FileOutputStream fileOut = new FileOutputStream("new_workbook.xls");
      writeWorkbook.write(fileOut);
      fileOut.close();
    }
    catch(FileNotFoundException e)
    {
      System.out.println(e);
    }
    catch(IOException e)
    {
      System.out.println(e);
    }
    catch(InvalidFormatException e)
    {
      System.out.println(e);
    }
 
  }
}

Removing all characters but letters and numbers

/**
 * Removing all characters but letters and numbers.
 * @author Xuan Ngo
 *
 */
public class StrippingUnwantedChars
{
 
  public static void main(String[] args)
  {
    String s = "Good Morning, today is 1900-12-31.";
 
    /**
     * Replace characters that are NOT lowercase letters(a-z), uppercase 
     *  letters(A-Z) or numbers(0-9) with empty string.
     */
    s = s.replaceAll("[^a-zA-Z0-9]", "");
 
    System.out.println(s); // Output: GoodMorningtodayis19001231
  }
 
}

Sort object with different values using comparators

/**
 * Show multiple ways to sort objects with different values. 
 * @author Xuan Ngo
 */
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
public class SortingUsingComparator
{
 
  public static void main(String[] args)
  {
    /**
     * Create data
     */
    Person a = new Person();
    Person b = new Person();
    Person c = new Person();
    Person d = new Person();
    a.firstname = "chris";  a.lastname = "bourgois";
    b.firstname = "betty";  b.lastname = "smith";
    c.firstname = "daniel"; c.lastname = "lopez";
    d.firstname = "alain";  d.lastname = "gonzalez";
    Person[] aPersons = {a, b, c, d}; // The ARRAY
 
    ArrayList<Person> lPersons = new ArrayList<Person>(); // The LIST
    lPersons.add(a); lPersons.add(b); lPersons.add(c); lPersons.add(d); 
 
    /**
     * First alternative.
     * Sort ARRAY by firstname using FirstnameComparator class.
     */
    System.out.println("Sort array by first name in ascending order:");
    Arrays.sort(aPersons, new FirstnameComparator());
    displayPersonsArray(aPersons);
 
    /**
     * Second alternative.
     * Sort LIST by firstname using FirstnameComparator class.
     */
    System.out.println("Sort list by first name in ascending order:");
    Collections.sort(lPersons, new FirstnameComparator());
    displayPersonsList(lPersons);
 
    /**
     * Third alternative.
     * Sort ARRAY by lastname in descending order with instant creation of comparator.
     */
    System.out.println("Sort by last name in descending order:");
    Arrays.sort(aPersons, new Comparator<Person>()
                  {
                    public int compare(Person p1, Person p2)
                    {
                      return p2.lastname.compareTo(p1.lastname);
                    }                
                  }
                );
    displayPersonsArray(aPersons);
 
 
  }
 
  /**
   * Display person info.
   * @param aPersons
   */
  public static void displayPersonsArray(Person[] aPersons)
  {
    for(int i=0; i<aPersons.length; i++)
    {
      String s = String.format("\t%s. %s %s", i, aPersons[i].firstname, aPersons[i].lastname);
      System.out.println(s);
    }
  }
  /**
   * Display person info.
   * @param lPersons
   */
  public static void displayPersonsList(ArrayList<Person> lPersons)
  {
    for(int i=0; i<lPersons.size(); i++)
    {
      String s = String.format("\t%s. %s %s", i, lPersons.get(i).firstname, lPersons.get(i).lastname);
      System.out.println(s);
    }
  }
}
/**
 * Person.java
 * Simple object that we want to sort.
 */
public class Person
{
  public String firstname, lastname;
}
/**
 * FirstnameComparator.java
 */
import java.util.Comparator;
 
/**
 * Implementation of Comparator class for Person.
 * Sort only by firstname in alphabetic order. 
 */
public class FirstnameComparator implements Comparator<Person>
{
  public int compare(Person p1, Person p2)
  {
    return p1.firstname.compareTo(p2.firstname);
  }
}
AttachmentSize
Package icon SortingUsingComparator.zip1.42 KB

Take screenshots of the full screen

/**
 * Take screenshots of the full screen.
 *  Usage: java PrintScreen <wait_in_milliseconds> <save_to_directory> <filename_prefix>
 * @author Xuan Ngo
 */
 
import java.awt.Toolkit;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
 
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import javax.imageio.ImageIO;
 
public class PrintScreen
{
  public static void main(String[] args)
  {
    // Print help how to use this application.
    if (args.length != 3)
    {
      System.out.println("Usage:\n java PrintScreen <wait_in_milliseconds> <save_to_directory> <filename_prefix>\n");
      System.out.println("Examples:");
      System.out.println(" In MS Windows: java PrintScreen 1000 c:\\myPictureDirectory myScreenshotPrefix");
      System.out.println(" In Linux: java PrintScreen 1000 /myPictureDirectory myScreenshotPrefix");
      System.exit(0);
    }
 
    // Get arguments.
    long lWaitTime = Long.parseLong(args[0]);
    File oDir = new File(args[1]);
    String sPrefix = args[2];
 
    String sDirectory = "";
    try
    {
      sDirectory = oDir.getCanonicalPath();
    }
    catch (IOException ex)
    {
      System.out.println(ex.getMessage());
    }
 
    // Take screenshots of the full screen forever.
    PrintScreen oPrintScreen = new PrintScreen();
    while (true)
    {
      String sPathSeparator = "";
      if (!sDirectory.endsWith(File.separator))
      {
        sPathSeparator = File.separator;
      }
      final String sCurrentDateTime = oPrintScreen.getCurrentDataTime();
      final String sFilename = sDirectory + sPathSeparator + sPrefix + "_" + sCurrentDateTime + ".png";
      oPrintScreen.captureScreen(sFilename);
      try
      {
        // Waiting time between each screenshot.
        Thread.sleep(lWaitTime);
      }
      catch (Exception ex)
      {
        System.out.println(ex.getMessage());
      }
    }
 
  }
 
  public void captureScreen(final String sFilename)
  {
    try
    {
      // Determine current screen size
      Toolkit toolkit = Toolkit.getDefaultToolkit();
      Dimension oScreenSize = toolkit.getScreenSize();
      Rectangle oScreen = new Rectangle(oScreenSize);
 
      // Create screen shot
      Robot robot = new Robot();
      BufferedImage oImage = robot.createScreenCapture(oScreen);
 
      // Save captured image to PNG file
      ImageIO.write(oImage, "png", new File(sFilename));
 
      // Display info of image saved.
      String sMsg = String.format("Screenshot(%s x %s pixels) is saved to %s.", oImage.getWidth(), oImage.getHeight(), sFilename);
      System.out.println(sMsg);
    }
    catch (Exception ex)
    {
      System.out.println(ex.getMessage());
      System.exit(0); // Shutdown the application completely. Need this because of the infinite loop.
    }
  }
 
  public final String getCurrentDataTime()
  {
    Date oCurrentDate = new Date();
    SimpleDateFormat oSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss.SSSS");
    return oSimpleDateFormat.format(oCurrentDate);
  }
}

Use ResourceBundle and properties files to add multilanguage support to your application

import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import java.io.FileOutputStream;
 
/**
 * Show how to use ResourceBundle and properties files to add multilanguage 
 * support to your application.
 * Note: You will get the following error message:
 * java.util.MissingResourceException Can't find bundle for base name, locale...
 * If the properties are not placed at the right place. Here are the solutions:
 * 
 * 1)
 * Copy all properties into the build folder(e.g. bin\ folder)
 * or
 * 2)
 * In eclipse, add the root folder of your project in Run Configurations->Classpath->User Entries.
 *  Click on the Advancesd... button.
 *  Select the Add Folders.
 *  Select the root folder of your project.
 *  Click on the OK button.
 * @author Xuan Ngo
 */
public class MultiLangualProperties
{
 
  public static void main(String[] args)
  {
    MultiLangualProperties oMp = new MultiLangualProperties();
    oMp.createProperties();
 
    // Load properties files.
    ResourceBundle oEnRBundle = ResourceBundle.getBundle("myproperties", Locale.ENGLISH);
    ResourceBundle oFrRBundle = ResourceBundle.getBundle("myproperties", Locale.FRENCH);
 
    String s = String.format("French equivalent of '%s' is '%s'.", oEnRBundle.getString("dog"), oFrRBundle.getString("dog"));
    System.out.println(s); // The output: French equivalent of 'dog' is 'chien'.
  }
  /**
   * Create all properties files.
   */
  public void createProperties()
  {
    this.createBaseProperty();
    this.createFrenchProperty();
  }
 
  /**
   * Create base properties file.
   */
  public void createBaseProperty()
  {
    // Create the properties object and add some values.
    Properties oWriteProperties = new Properties();
    oWriteProperties.setProperty("dog", "dog");
 
    // Save properties into file. 
    try
    {
      oWriteProperties.store(new FileOutputStream("myproperties.properties"), "Base properties");
    }
    catch(Exception ex)
    {
      System.out.println(ex.getMessage());
    }
  }
 
  /**
   * Create french properties file.
   */
  public void createFrenchProperty()
  {
    // Create the properties object and add some values.
    Properties oWriteProperties = new Properties();
    oWriteProperties.setProperty("dog", "chien");
 
    // Save properties into file. 
    try
    {
      oWriteProperties.store(new FileOutputStream("myproperties_fr.properties"), "French properties");
    }
    catch(Exception ex)
    {
      System.out.println(ex.getMessage());
    }
  }    
}

Troubleshooting reference: http://javahowto.blogspot.com/2006/05/debug-java-util-missingresourceexcepti.html

Use cURL in Windows to send UTF8 JSON data in ElasticSearch

curl -X PUT "http://localhost:9200/movies/movie/11" --data "@the.grand.canal.txt"

The the.grand.canal.txt file looks like the following:

{
    "title": "大運河",
    "year": 1987,
    "genres": ["Adventure", "Drama"],
    "actors": ["Bobby Au Yeung Chun Wah", "蘭陵公主", "Tony Leung Chiu Wai"]
}

Reference: http://joelabrahamsson.com/elasticsearch-101/

Uses of regular expression in String.replaceAll()

package net.xngo.tutorial.java.string;
 
/**
 * Show how to use regular expression in String.replaceAll().
 * @author Xuan Ngo
 *
 */
public class ReplaceAllRegex
{
 
  public static void main(String[] args) 
  {
    String s = "";
 
    /*
     * Remove substring that ends with ,???$
     * Show how to escape and use $.
     */
    s = "53 001,88 $";
    s = s.replaceAll(",...\\$$", "\\$");
    System.out.println(s); // Output: 53 001$
 
    /*
     * Replace a substring regardless of its characters' case(Case Insensitive).
     */
    s = "CaSE Insensitive";
    s = s.replaceAll("(?i)case", "Case");
    System.out.println(s); // Output: Case Insensitive
 
    /*
     * Show how to use backreferences, reuse the matched pattern.
     */
    s = "High Medium Low";
    s = s.replaceAll("(High) (Medium) (Low)", "$3 $2 $1");
    System.out.println(s); // Output: Low Medium High
 
    /*
     * Replace all adjacent wildcard(*) with 1 wildcard(*).
     */
    s = "multiple****wild***card*";
    s = s.replaceAll("[\\*\\*]+", "*");
    System.out.println(s); // Output: multiple*wild*card*
 
 
  }
 
}

https://github.com/xuanngo/Tutorial/blob/master/src/net/xngo/tutorial/java/string/ReplaceAllRegex.java

// Separate words by capital letters JAVA: s.replaceAll("((?<=[a-z])[A-Z]|A-Z)", " $1"); PHP: preg_replace('((?<=[a-z])[A-Z]|A-Z)', ' \0', $string);

Write text to file

/**
 * Show how to write text to file.
 * @author Xuan Ngo
 */
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
 
public class WriteToFile
{
  public static void main(String[] args)
  {
    try
    {
      FileWriter oFileWriter = new FileWriter("filename.txt");
      BufferedWriter oBufferedWriter = new BufferedWriter(oFileWriter);
      oBufferedWriter.write("Java");
      oBufferedWriter.close();
    }
    catch(IOException ex)
    {
      System.out.println(ex.getMessage());
    } 
  }
 
}

log4j

http://ideoplex.com/id/386/controlling-hibernate-output-with-log4j

http://www.laliluna.de/articles/log4j-tutorial.html

http://juliusdavies.ca/logging.html

http://www.vaannila.com/log4j/log4j-configuration.html

import org.apache.log4j.Logger;  
 
public class YourClass
{ 
  // Some people recommend against making this line static but Logger.getLogger() 
  //  is synchronized, so non-static can degrade performance.  
  private static final Logger log = Logger.getLogger(YourClass.class)  
 
 
  public void someMethod() 
  {  
    log.info("Your info message");  
  }  
} 

Compress log file http://jajatips.blogspot.com/2009/08/writing-compressing-file-appender-for.html

"yyyy-MM-dd/HH:mm:ss.SSS/zzz"

Create 1 log file per day

Add the followings in your Log4j configuration/properties file:

log4j.rootLogger=info, R
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=filename
log4j.appender.R.DatePattern='.'yyyy-MM-dd'.log'
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS zzz} %5p %c{1}:%L - %m%n

The filename of the log file will look like this:

filename
filename.2010-01-21.log
filename.2010-01-22.log
filename.2010-01-23.log

Manipulate directory and file path in portable way

/**
 * Show how to manipulate directory and file path in portable way. 
 * @author Xuan Ngo
 */
import java.io.File;
import java.io.IOException;
 
public class DirFileHandling
{
  public static void main(String[] args)
  {
    // Get current directory path
    File oFile = new File(".");
    String sCurrDirPath = "";
    try
    {
      sCurrDirPath = oFile.getCanonicalPath();
      System.out.println(sCurrDirPath);
    }
    catch(IOException ex)
    {
      System.out.println(ex.getMessage());
    }
 
    // Create the path of a new sub-directory.
    String sNewDirPath = sCurrDirPath + File.separator  + "NewDirName";
    System.out.println(sNewDirPath);
 
    // Create the path of a file under the sub-directory.
    String sNewFilePath = sCurrDirPath + File.separator + "NewDirName"+ File.separator + "NewFileName.txt";
    System.out.println(sNewFilePath);
 
  }
 
}

Multithreaded Programming

/**
 * Manager.java
 * Multithreaded example:
 * Give a job to each worker. As soon as a worker finishes his job, assign a new 
 *  job to the free worker.
 * @author Xuan Ngo
 */
import java.util.ArrayList;
 
public class Manager
{
  public static void main(String[] args)
  {
    // Variables
    int iNumOfWorkers = 3;// Number of workers.
    int iNumOfJobs = 11;  // Number of jobs.
    long lWaitTime = 1000;// Time lapse before asking who workers are free.
 
    // Create jobs list.
    ArrayList<String> aJobsList = new ArrayList<String>();
    for(int j=0; j<iNumOfJobs; j++)
      aJobsList.add((j+1)+"");
 
    // Create workers
    Worker aWorkers[] = new Worker[iNumOfWorkers];
    for(int i=0; i<iNumOfWorkers; i++)
    {
      aWorkers[i] = new Worker();
    }
 
 
    System.out.println("Start giving jobs to workers("+aJobsList.size()+" jobs)");    
 
    // Work until there is no job left.
    while(aJobsList.size()>0)
    {
      // Get a list of which workers are free.
      ArrayList<Integer> aFreeWorkersIndex = getFreeWorkers(aWorkers);
 
      // Show free workers.
      displayFreeWorkers(aFreeWorkersIndex);
 
      // Give each worker a job.
      for(int j=0; j<aFreeWorkersIndex.size(); j++)
      {
        int iWorkerId = aFreeWorkersIndex.get(j).intValue();
        aWorkers[iWorkerId] = new Worker();
 
        // Custom method used to pass data to the worker.
        aWorkers[iWorkerId].set("Worker"+iWorkerId, aJobsList);
 
        aWorkers[iWorkerId].start();
      }
 
      // Wait X time before asking who are free to take a job.
      try
      {
        Thread.sleep(lWaitTime);
      }
      catch(Exception ex)
      {
        System.out.println(ex);
      }
    }
 
    System.out.println("End giving jobs to workers.");
 
  }
 
  /**
   * Get the id of workers that are free.
   * @param aWorkers
   * @return IDs of workers that are free.
   */
  public static ArrayList<Integer> getFreeWorkers(Worker aWorkers[])
  {
    ArrayList<Integer> aFreeWorkersIndex = new ArrayList<Integer>();
 
    // Go through each worker and see who are free to take new job.
    for(int i=0; i<aWorkers.length; i++)
    {
      if(!aWorkers[i].isAlive())
      {
        aFreeWorkersIndex.add(new Integer(i));
      }
    }
    return aFreeWorkersIndex;
  }
 
  public static void displayFreeWorkers(ArrayList<Integer> aWorkers)
  {
    // No free workers. Get out.
    if(aWorkers.size()==0)
    {
      System.out.println("No free workers.");
      return;
    }
 
    // Display free workers.
    System.out.print("Free workers IDs: ");
    for(int i=0; i<aWorkers.size()-1; i++)
      System.out.print(aWorkers.get(i)+", ");
    System.out.print(aWorkers.get(aWorkers.size()-1)); // Display last worker's ID.
    System.out.println();
  }
}







/**
 * Worker.java
 * Implement what worker should do in this class.
 * @author Xuan Ngo
 */
import java.lang.Thread;
import java.util.Random;
import java.util.ArrayList;
 
public class Worker extends Thread 
{
  private String m_sWorkerName = "";
  private ArrayList<String> m_aJobsList = null;
  private String m_sJobName = "";
 
  public Worker()
  {}
 
  /**
   * Demonstrate how to pass values from Manager class to Worker class.
   * @param sWorkerName
   * @param aJobsList
   */
  public void set(String sWorkerName, ArrayList<String> aJobsList)
  {
    this.m_sWorkerName = sWorkerName;
    this.m_aJobsList = aJobsList;
 
    this.getJob();
  }
  /**
   * Get the job and remove it from the job list so that other workers will
   *  not take the same job.
   * Synchronized keyword is used so that other workers can't take the same job.
   */
  private synchronized void getJob()
  {
    if(this.m_aJobsList.size()!=0)
      this.m_sJobName = this.m_aJobsList.remove(0);
  }
 
  /**
   * This method will run when Worker.start() is called.
   * All the logics should be put in here. This is like the main() of a program.
   */
  public void run()
  {
    /**
     * Put a random sleep time to simulate work time.
     */
    Random oRandom = new Random();
    int iSleepTime = oRandom.nextInt(5000);
    System.out.println("\t"+this.m_sWorkerName+": Working on Job"+this.m_sJobName+" for " +iSleepTime +"ms.");
    try
    {
      Thread.sleep(iSleepTime);
    }
    catch(Exception ex)
    {
      System.out.println(ex);
    }
    System.out.println("\t"+this.m_sWorkerName+": Done Job"+this.m_sJobName+".");
  }
 
}
AttachmentSize
File Manager.java2.87 KB
File Worker.java1.66 KB

Parameterized String / Format String

package net.xngo.tutorial.java.lang;
 
import java.util.Calendar;
 
/**
 * Add variable values in a string.
 * @author Xuan Ngo
 *
 */
public class ParameterizedString
{
  public static void main(String[] args)
  {
    int        i = 142343;
    long       l = 454374587;
    float      f = 2.99f;
    double     d = 987663.90432;
    char       c = 'x';
    String     s = "String";
    Calendar now = Calendar.getInstance();
 
    // Simple parameterized string.
    String pString = String.format("Parameterized string examples: \n"
            + "\t Integer = %d    \n"
            + "\t Long    = %d    \n"
            + "\t Float   = %f    \n"
            + "\t Double  = %f    \n"
            + "\t Char    = %c    \n"
            + "\t String  = %s    \n"
            + "\t Now     = %tF   \n"
              , i, l, f, d, c, s, now);
    System.out.println(pString);
 
    // Show different useful features.
    pString = String.format("Parameterized string examples: \n"
            + "\t Integer = %,d     \n" // Add thousand separator.
            + "\t Long    = %d      \n"
            + "\t Float   = %f      \n"
            + "\t Double  = %.2f    \n" // Show only 2 decimal points.
            + "\t Char    = %c      \n"
            + "\t String  = %s      \n"
            + "\t Now     = %tF     \n" // YYYY-MM-DD
            + "\t Argument= %2$d    \n" // Get the value of the 2nd input argument/parameter.
            , i, l, f, d, c, s, now);
    System.out.println(pString);
 
    // Show mix of useful features.
    pString = String.format("Parameterized string examples: \n"
            + "\t Zero padding             = %09d  \n"  // Pad zeros so the length is 9 digits.
            + "\t Decimal Point / Thousand = %,.2f \n"  // Add thousand separator(,) and decimal point(.).
            , i, d);
    System.out.println(pString);    
 
  }
 
}

Reference: https://github.com/xuanngo/Tutorial/blob/master/src/net/xngo/tutorial/java/lang/ParameterizedString.java

Performance of primitive data type vs object data type

Using the object data type instead of its primitive counter part is very expensive. In fact, object data type is approximatively 43 times slower than its primitive counter part. However, I have to scale up to 1 billion iterations to see the difference.

/**
 * Performance of primitive data type vs object data type.
 * @author Xuan Ngo
 *
 */
public class PrimitiveVsObject
{
  public static void main(String[] args)
  {
    long lStart = 0;
    long lEnd = 0;
    int lMaxSize = 1000000000; // 1 billion.
 
    // Primitive data type
    System.out.print("Primitive data type runtime: ");
    lStart = System.currentTimeMillis();
    for(int i=0; i<lMaxSize; i++)
    {
     int test = i; 
    }
    lEnd = System.currentTimeMillis();
    System.out.println(lEnd-lStart);
    // Output: Primitive data type runtime: ~2454
 
 
    // Object data type
    System.out.print("Object data type runtime: ");
    lStart = System.currentTimeMillis();
    for(int i=0; i<lMaxSize; i++)
    {
     Integer test = new Integer(i); 
    }
    lEnd = System.currentTimeMillis();
    System.out.println(lEnd-lStart); 
    // Output: Object data type runtime: ~106593
 
  }
 
}