singleton
When several threads access a Singleton is has to be thread-safe and should cause as few locks as possible. Using lazy-loading, this can be achieved through double-checked locking (DCL). Though, in the literature you will find quite sophisticated articles explaining why DCL is not guaranteed by the JVM specs to work correctly.
download example

public class Singleton
{
  private static Singleton sSingleton;

  private Singleton()
  {
    ...
  }

  public static Singleton instance()
  {
    if(sSingleton == null)
    {
      synchronized(Singleton.class)   // you only have to synchronize once
      {
        if(sSingleton == null)
        {
          sSingleton = new Singleton();
        }
      }
    }
    return sSingleton;
  }
}

singleton unit test
In order to test a Singleton for thread-safety you can start with the follwoing JUnit test case template. There is no guarantee for correctness, though.
download example

public void testThread()
{
  TestThread[] threads = new TestThread[NUMOFTHREADS];
  for(int i=0; i<NUMOFTHREADS; i++)
  {
    threads[i] = new TestThread();
    threads[i].start();
  }

  for(int i=0; i<NUMOFTHREADS; i++)
  {
    try
    {
      threads[i].join();
    }
    catch(InterruptedException e)
    {
      fail("Interrupted Thread " + i);
    }
  }

  for(int i=0; i<NUMOFTHREADS-1; i++)
  {
    assertSame("thread " + i, threads[i].fSingleton, threads[i+1].fSingleton);
  }
}

class TestThread extends Thread
{
  private Singleton fSingleton;

  public void run()
  {
    fSingleton = Singleton.instance();
  }
}

read from and write to classpath
Sometimes it is necessary to read from a file on the classpath or write to a file that is already on the classpath.
download example

// read from classpath
InputStream is = CpReadAndWrite.class.getResourceAsStream(FILENAME);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
content = reader.readLine();
...
// write to classpath
String absolutePath = CpReadAndWrite.class.getResource(FILENAME).getPath();
PrintWriter writer = new PrintWriter((new FileOutputStream(absolutPath)));
writer.println(content);

array casting
In some situation elements of the same class are added to a collection. The collection's elements can then be retrieved as an array of the elements' class (and not only as an array of Object).
download example

fList = new Vector();
for(int i=0; i<10; i++)
{
  ...
  fList.add("item " + i);
  ...
}
...
return (String[]) fList.toArray(new String[fList.size()]);

reflection
Reflection is very powerful in Java. It allows at runtime to retrieve all kind of information about a class like its methods, its super class, etc...
download example

Vector vector = new Vector();
Method[] methods = vector.getClass().getDeclaredMethods();
for(int i=0; i<methods.length; i++)
{
  Method method = methods[i];
  String methodName = method.getName();
  String modifiers = Modifier.toString(method.getModifiers());
  String returnType = method.getReturnType().getName();
  Class[] parameters = method.getParameterTypes();
  Class[] exceptions = method.getExceptionTypes();
  ...
  System.out.println(modifiers + " " + returnType + " " + methodName + ... );
}

In addition to retrieving information about a class, it is possible to invoke methods, instantiate classes, and change field values.
download example

myClass = Class.forName("java.lang.Integer");
parameterTypes = new Class[]{String.class, int.class};
method = myClass.getMethod("parseInt", parameterTypes);
parameters = new Object[]{"FF", new Integer(16)};
Integer number = (Integer) method.invoke(null, parameters);
System.out.println(number.intValue());

There is even the possibility to access fields, constructors, and methods that have only private access.
download example

// the method getIterator has only private access
Class myClass = Class.forName("java.util.Hashtable");
Method method = myClass.getDeclaredMethod("getIterator", new Class[]{Integer.TYPE});
method.setAccessible(true);
Iterator iterator = (Iterator) method.invoke(new Hashtable(), new Object[]{new Integer(1)});

execute external applications
There is the possibility to execute external applications from within your Java application and wait for the executed application to finish before continuing with your Java program.
download example

Process p = Runtime.getRuntime().exec("notepad");
try
{
  p.waitFor();
}
catch(InterruptedException ie)
{
  System.out.println(ie);
}
int ret = p.exitValue();

find location of class file
Sometimes it helps to know the location from where a class file has been loaded.
download example

Class c = "foo".getClass();
String className = c.getName();
String resourceName = "/" + className.replace('.', '/') + ".class";
URL location = c.getResource(resourceName);
System.out.println(location);

serializing into and deserializing from string
An object can be serialized into a string and later be deserialized from that string again. Compression is also easy to include in order to keep the string shorter.
download example

// serialize object into a string
Object toSerialize = ...

ByteArrayOutputStream arrayStream = new ByteArrayOutputStream();
GZIPOutputStream zipStream = new GZIPOutputStream(arrayStream);
ObjectOutputStream objectStream = new ObjectOutputStream(zipStream);

objectStream.writeObject(toSerialize);
byte[] serialized = arrayStream.toByteArray();
String s = new String(serialized, "ISO-8859-1");
...
// deserialize object from string
String toDeserialize = ...
byte[] serialized = toDeserialize.getBytes("ISO-8859-1");

ByteArrayInputStream arrayStream = new ByteArrayInputStream(serialized);
GZIPInputStream zipStream = new GZIPInputStream(arrayStream);
ObjectInputStream objectStream = new ObjectInputStream(zipStream);

Object o = objectStream.readObject();

serializing into and deserializing from pseudo.xml
There is a library called Java Serialization for XML (JSX) that allows to serialize any object into pseudo-XML and later deserialize it from pseudo-XML again.
download example

// serialize object into a string
Object toSerialize = ...
StringWriter writer = new StringWriter();
ObjOut out = new ObjOut(false, writer);
out.writeObject(toSerialize);
String s = writer.toString();
...
// deserialize object from string
String toDeserialize = ...
StringReader reader = new StringReader(toDeserialize);
ObjIn in = new ObjIn(reader);
Object o = in.readObject();

number crunching
In high school I often forgot to do my homework and my math teacher always made calculate twenty to the power of four. If there had been Java back then...
download example

// not exact enough
for(int i = 0; i < 21; i++) {
  double pow = Math.pow(4, i);
  System.out.println("4^" + i + " = " + pow);
}
...
// exact
for(int i = 0; i < 21; i++) {
 BigInteger pow = BigInteger.valueOf(4).pow(i);
 System.out.println("4^" + i + " = " + pow);
}

swing look & feel
You can define the default look & feel of your Swing application on the command line by setting a system property.

java -Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel MyApplication