stuff - java tricks

Hidden Features of Java (20)

After reading Hidden Features of C# I wondered, What are some of the hidden features of Java?

A couple of people have posted about instance initializers, here's a good use for it:

Map map = new HashMap() {{
    put("a key", "a value");
    put("another key", "another value");

Is a quick way to initialize maps if you're just doing something quick and simple.

Or using it to create a quick swing frame prototype:

JFrame frame = new JFrame();

JPanel panel = new JPanel(); 

panel.add( new JLabel("Hey there"){{ 
    setForeground( Color.white);

panel.add( new JButton("Ok"){{
    addActionListener( new ActionListener(){
        public void actionPerformed( ActionEvent ae ){
            System.out.println("Button pushed");

 frame.add( panel );

Of course it can be abused:

    JFrame frame = new JFrame(){{
         add( new JPanel(){{
               add( new JLabel("Hey there"){{ 
                    setForeground( Color.white);

                add( new JButton("Ok"){{
                    addActionListener( new ActionListener(){
                        public void actionPerformed( ActionEvent ae ){
                            System.out.println("Button pushed");

Allowing methods and constructors in enums surprised me. For example:

enum Cats {
  FELIX(2), SHEEBA(3), RUFUS(7);

  private int mAge;
  Cats(int age) {
    mAge = age;
  public int getAge() {
    return mAge;

You can even have a "constant specific class body" which allows a specific enum value to override methods.

More documentation here .

Every class file starts with the hex value 0xCAFEBABE to identify it as valid JVM bytecode.

( Explanation )

Haven't seen anyone mention instanceof being implemented in such a way that checking for null is not necessary.

Instead of:

if( null != aObject && aObject instanceof String )

just use:

if( aObject instanceof String )

How about covariant return types which have been in place since JDK 1.5? It is pretty poorly publicised, as it is an unsexy addition, but as I understand it, is absolutely necessary for generics to work.

Essentially, the compiler now allows a subclass to narrow the return type of an overridden method to be a subclass of the original method's return type. So this is allowed:

class Souper {
    Collection<String> values() {

class ThreadSafeSortedSub extends Souper {
    ConcurrentSkipListSet<String> values() {

You can call the subclass's values method and obtain a sorted thread safe Set of String s without having to down cast to the ConcurrentSkipListSet .

I was surprised by instance initializers the other day. I was deleting some code-folded methods and ended up creating multiple instance initializers :

public class App {
    public App(String name) { System.out.println(name + "'s constructor called"); }

    static { System.out.println("static initializer called"); }

    { System.out.println("instance initializer called"); }

    static { System.out.println("static initializer2 called"); }

    { System.out.println("instance initializer2 called"); }

    public static void main( String[] args ) {
        new App("one");
        new App("two");

Executing the main method will display:

static initializer called
static initializer2 called
instance initializer called
instance initializer2 called
one's constructor called
instance initializer called
instance initializer2 called
two's constructor called

I guess these would be useful if you had multiple constructors and needed common code

They also provide syntactic sugar for initializing your classes:

List<Integer> numbers = new ArrayList<Integer>(){{ add(1); add(2); }};

Map<String,String> codes = new HashMap<String,String>(){{ 

JDK 1.6_07+ contains an app called VisualVM (bin/jvisualvm.exe) that is a nice GUI on top of many of the tools. It seems more comprehensive than JConsole.

Language-level assert keyword.

My favorite: dump all thread stack traces to standard out.

windows: CTRL - Break in your java cmd/console window

unix: kill -3 PID

Not really a feature, but an amusing trick I discovered recently in some Web page:

class Example
  public static void main(String[] args)
    System.out.println("Hello World!");


is a valid Java program (although it generates a warning). If you don't see why, see Gregory's answer! ;-) Well, syntax highlighting here also gives a hint!

Not really part of the Java language, but the javap disassembler which comes with Sun's JDK is not widely known or used.

The addition of the for-each loop construct in 1.5. I <3 it.

// For each Object, instantiated as foo, in myCollection
for(Object foo: myCollection) {

And can be used in nested instances:

for (Suit suit : suits)
  for (Rank rank : ranks)
    sortedDeck.add(new Card(suit, rank));

The for-each construct is also applicable to arrays, where it hides the index variable rather than the iterator. The following method returns the sum of the values in an int array:

// Returns the sum of the elements of a
int sum(int[] a) {
  int result = 0;
  for (int i : a)
    result += i;
  return result;

Link to the Sun documentation

The type params for generic methods can be specified explicitly like so:


Transfer of control in a finally block throws away any exception. The following code does not throw RuntimeException -- it is lost.

public static void doSomething() {
    try {
      //Normally you would have code that doesn't explicitly appear 
      //to throw exceptions so it would be harder to see the problem.
      throw new RuntimeException();
    } finally {


Using this keyword for accessing fields/methods of containing class from an inner class. In below, rather contrived example, we want to use sortAscending field of container class from the anonymous inner class. Using ContainerClass.this.sortAscending instead of this.sortAscending does the trick.

import java.util.Comparator;

public class ContainerClass {
boolean sortAscending;
public Comparator createComparator(final boolean sortAscending){
    Comparator comparator = new Comparator<Integer>() {

        public int compare(Integer o1, Integer o2) {
            if (sortAscending || ContainerClass.this.sortAscending) {
                return o1 - o2;
            } else {
                return o2 - o1;

    return comparator;

You can define an anonymous subclass and directly call a method on it even if it implements no interfaces.

new Object() {
  void foo(String s) {

You can use enums to implement an interface.

public interface Room {
   public Room north();
   public Room south();
   public Room east();
   public Room west();

public enum Rooms implements Room {
   FIRST {
      public Room north() {
         return SECOND;
      public Room south() {
         return FIRST;

   public Room north() { return null; }
   public Room south() { return null; }
   public Room east() { return null; }
   public Room west() { return null; }

EDIT: Years later....

I use this feature here

public enum AffinityStrategies implements AffinityStrategy {

By using an interface, developers can define their own strategies. Using an enum means I can define a collection (of five) built in ones.

Dynamic proxies (added in 1.3) allow you to define a new type at runtime that conforms to an interface. It's come in handy a surprising number of times.

Double Brace Initialization took me by surprise a few months ago when I first discovered it, never heard of it before.

ThreadLocals are typically not so widely known as a way to store per-thread state.

Since JDK 1.5 Java has had extremely well implemented and robust concurrency tools beyond just locks, they live in java.util.concurrent and a specifically interesting example is the java.util.concurrent.atomic subpackage that contains thread-safe primitives that implement the compare-and-swap operation and can map to actual native hardware-supported versions of these operations.