Subtracting days from a date

The following example subtracts 200 days from the current date.

Main.java:

import java.util.*;
 
public class Main
{
   public static void main(String []args) {
      Calendar cal = Calendar.getInstance();
      cal.setTime(new Date());
      int year  = cal.get(Calendar.YEAR);
      int month = cal.get(Calendar.MONTH);
      int day   = cal.get(Calendar.DATE);
      month++;   // months are from 0-11, so add one!
 
      printDate(cal);
 
      cal.add(Calendar.DATE, -200);
 
      printDate(cal);
   }
 
   public static void printDate(Calendar cal) {
      System.out.println((cal.get(Calendar.MONTH)+1) + "-" +
                         cal.get(Calendar.DATE) + "-" +
                         cal.get(Calendar.YEAR));
   }
}

outputs:

4-28-2002
10-10-2001

Keeping track of line numbers when reading a file with a Reader

Use the class filtered reader LineNumberReader. While getting the actual read buffer from the reader, you can also retrieve the current line number. You can also (re)set it with setLineNumber. This does not affect the file pointer.

This example reads in a textfile and displays a separator line every 10 lines.

Main.java:

import java.io.*;
  
public class Main {
   public static void main(String args[]) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <textfile>");
         System.exit(1);
      }
  
      try {
         LineNumberReader lnr = new LineNumberReader(new FileReader(args[0]));
         String line;
         while ((line = lnr.readLine()) != null) {
            if ((lnr.getLineNumber() % 10) == 0)
               System.out.println("------------------------------------------");
            System.out.println(line);
         }
      }
      catch(IOException e) {
         System.out.println(e);
      }
   }
}

Using a filter when listing the contents of a directory in Java

The easiest way is to use an anonymous inner class which implements either FileFilter or FilenameFilter:

//list only pdf files
File[] pdfFiles = departmentFolder.listFiles(new FilenameFilter(){
  public boolean accept(File dir, String name){
    return (name.endsWith("pdf")||name.endsWith("PDF"));
  }
});
//list only folders
File[] usrFolders = departmentFolder.listFiles(new FileFilter(){
  public boolean accept(File pathname){
    return (pathname.isDirectory());
  }
});

Determining the Java version at runtime

Try this:

import java.util.*;
import java.text.*;
import java.io.*;
 
public class Main10
{
   public static void main(String [] args) throws Exception {
      String vendor = System.getProperty("java.vendor");
      String version = System.getProperty("java.version");
  
      System.out.println("vendor: " + vendor + "nversion: " + version);
   }
}

output like:

vendor: Sun Microsystems Inc.
version: 1.2.2

Converting an int to a boolean

Assuming 0 maps to false, 1 to true.

Main.java:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      System.out.println(int2Boolean(0));
      System.out.println(int2Boolean(1));
   }
 
   public static boolean int2Boolean(int a) {
      return a != 0;
   }
}

Increasing the size of an array

You can’t. You will have to create a new bigger array and copy the original one into it. A fast array copy can be achieved with System.arraycopy.

In the following example, we create an integer array of size 10 and increase it to 20.

Main.java:

public class Main {
   public static void main(String args[]) {
      int intArray[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 
      System.out.print("Before: ");
      printArray(intArray);
  
      intArray = enlargeIntArray(intArray, 20);
 
      System.out.print("After:  ");
      printArray(intArray);
   }
 
   public static int[] enlargeIntArray(int []intArray, int size) {
      // include code here to throw exception when intArray.length > size
 
      int newIntArray[] = new int[size];
      System.arraycopy(intArray, 0, newIntArray, 0, intArray.length);
      return newIntArray;            
   }
 
   public static void printArray(int []intArray) {
      for (int i=0; i<intArray.length; i++) {
         System.out.print(intArray[i] + " ");
      }
      System.out.println();
   }
}

outputs:

Before: 1 2 3 4 5 6 7 8 9 10 
After:  1 2 3 4 5 6 7 8 9 10 0 0 0 0 0 0 0 0 0 0

The problem with this code is that it is not very flexible. What if you want to increase the size of a String array? You would have to create a new similar method for that purpose. Java doesn’t include a Templates architecture, the first thing that would come to mind to solve this problem when programming in C++. However, you can use something fancy called reflection. The whole program evolves around the standard API class Array in which you can “dynamically” create and modify arrays, given the class type and the size.

Following example shows how to increase the size of an integer array and a float array with the same method.

Main.java:

import java.lang.reflect.*;
 
public class Main {
   public static void main(String args[]) {
      int intArray[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 
      System.out.print("Before: ");
      printArray(intArray);
      intArray = (int[]) enlargeArray(intArray, 20);
      System.out.print("After:  ");
      printArray(intArray);
 
      double doubleArray[] = new double[] { 0.9, 1.8, 2.7, 3.6, 4.5, 
                                            5.4, 6.3, 7.2, 8.1, 9.0 };
 
      System.out.print("Before: ");
      printArray(doubleArray);
      doubleArray = (double[]) enlargeArray(doubleArray, 20);
      System.out.print("After:  ");
      printArray(doubleArray);
   }
 
   public static Object enlargeArray(Object oldArray, int size) {
      // include code here to throw exception when oldArray.length > size
 
      Object newArray = Array.newInstance(oldArray.getClass().getComponentType(), size);
      System.arraycopy(oldArray, 0, newArray, 0, Array.getLength(oldArray));
      return newArray;
   }
 
   public static void printArray(Object array) {
      for (int i=0; i<Array.getLength(array); i++) {
         System.out.print(Array.get(array, i) + " ");
      }
      System.out.println();
   }
}

outputs:

Before: 1 2 3 4 5 6 7 8 9 10 
After:  1 2 3 4 5 6 7 8 9 10 0 0 0 0 0 0 0 0 0 0 
Before: 0.9 1.8 2.7 3.6 4.5 5.4 6.3 7.2 8.1 9.0 
After:  0.9 1.8 2.7 3.6 4.5 5.4 6.3 7.2 8.1 9.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 

Instantiating a class given its name as a String

Use Class.forName and newInstance on the resulting class object.

Look at the following example:

import java.lang.reflect.*;
 
public class Main {
   public static void main(String args[]) {
      try {
         Class c = Class.forName("MyClass");
         // create a new instance
         Object o = c.newInstance();
  
         // invoke a method on it
         Method m = c.getMethod("method1", new Class[] { });
         m.invoke(o, new Object[] { });
      }
      catch(ClassNotFoundException e) { 
         System.err.println(e);
      }
      catch(IllegalAccessException e) {
         System.err.println(e);
      }
      catch(InstantiationException e) { 
         System.err.println(e);
      }
      // for getMethod and invoke
      catch(NoSuchMethodException e) {
         System.err.println(e);
      }
      catch(InvocationTargetException e) {
         System.err.println(e);
      }
   }
}
 
class MyClass
{
   public void method1() {
      System.out.println("method1() called!");
   }
}

Using weak references in Java

A WeakReference is a type of a reference object that allows you to determine when an object is being finalized. It allows you to keep a reference to the object without preventing it from being garbage-collected. They are used with caching and also provide an alternative to the cleanup typically done in Java finalization.

Main.java:

import java.lang.ref.*;
import java.util.*;
import java.io.*;
   
public class Main {
   public static void main(String[] args) {
      System.out.println("Creating new object...");
      MyObject o = new MyObject();
 
      System.out.println("Starting thread that monitors the garbage collection of this object...");
      new ObjectSpy(o).start();
  
      System.out.println("Sleeping for 2 seconds...");
      sleep(2000);
 
      System.out.println("Making object null...");
      o = null;
 
      System.out.println("Filling up memory...");
      fillUpMemory();
   }
 
   public static void sleep(int millis) {
      try {
         Thread.sleep(millis);
      }
      catch(InterruptedException e) {
      }
   }
 
   public static void fillUpMemory() {
      LinkedList ll = new LinkedList();
      try {
         while (true) {
            ll.add(new Double[999999]);
         }
      } catch(OutOfMemoryError e) {
         ll.clear();
         System.gc();
      }
   }
}
 
class ObjectSpy extends Thread
{
   WeakReference wr;
 
   public ObjectSpy(Object o) {
      wr = new WeakReference(o);
   }
 
   public void run() {
      while (wr.get() != null) {
         try {
            Thread.sleep(1000);
         }
         catch(InterruptedException e) {}
      }
      System.out.println("ObjectSpy: object has been garbage collected!");
   }
}
 
class MyObject
{
   public void finalize() {
      System.out.println("MyObject being finalized...");
   }
} 

outputs:

Creating new object...
Starting thread that monitors the garbage collection of this object...
Sleeping for 2 seconds...
Making object null...
Filling up memory...
ObjectSpy: object has been garbage collected!
MyObject being finalized...

Remove leading and trailing whitespace from a String

Use the method trim(). It will create a new String but removes whitespace. Whitespace is defined as all Unicode characters less than or equal to “u0020″.

public class TestProg
{
    public static void main(String args[])
    {
        String s = "   t  Hello, world! ";
        System.out.println(s.trim());       // prints out: "Hello, world!"
    }
}