tricks Hidden Features of Java

java tricks (24)

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.

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

Language-level assert keyword.

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

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


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 Strings without having to down cast to the ConcurrentSkipListSet.

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.

final initialization can be postponed.

It makes sure that even with a complex flow of logic return values are always set. It's too easy to miss a case and return null by accident. It doesn't make returning null impossible, just obvious that it's on purpose:

public Object getElementAt(int index) {
    final Object element;
    if (index == 0) {
         element = "Result 1";
    } else if (index == 1) {
         element = "Result 2";
    } else {
         element = "Result 3";
    return element;

i personally discovered java.lang.Void very late -- improves code readability in conjunction with generics, e.g. Callable<Void>

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");

Joint union in type parameter variance:

public class Baz<T extends Foo & Bar> {}

For example, if you wanted to take a parameter that's both Comparable and a Collection:

public static <A, B extends Collection<A> & Comparable<B>>
boolean foo(B b1, B b2, A a) {
   return (b1.compareTo(b2) == 0) || b1.contains(a) || b2.contains(a);

This contrived method returns true if the two given collections are equal or if either one of them contains the given element, otherwise false. The point to notice is that you can invoke methods of both Comparable and Collection on the arguments b1 and b2.

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.

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 asList method in java.util.Arrays allows a nice combination of varargs, generic methods and autoboxing:

List<Integer> ints = Arrays.asList(1,2,3);

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!

When working in Swing I like the hidden Ctrl - Shift - F1 feature.

It dumps the component tree of the current window.
(Assuming you have not bound that keystroke to something else.)

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) {

I think another "overlooked" feature of java is the JVM itself. It is probably the best VM available. And it supports lots of interesting and useful languages (Jython, JRuby, Scala, Groovy). All those languages can easily and seamlessly cooperate.

If you design a new language (like in the scala-case) you immediately have all the existing libraries available and your language is therefore "useful" from the very beginning.

All those languages make use of the HotSpot optimizations. The VM is very well monitor and debuggable.

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


For most people I interview for Java developer positions labeled blocks are very surprising. Here is an example:

// code goes here

    for (int i = 0; i < N; ++i) {
        for (int j = i; j < N; ++j) {
            for (int k = j; k < N; ++k) {
                //do something here
                break getmeout;

Who said goto in java is just a keyword? :)

This is not exactly "hidden features" and not very useful, but can be extremely interesting in some cases:
Class sun.misc.Unsafe - will allow you to implement direct memory management in Java (you can even write self-modifying Java code with this if you try a lot):

public class UnsafeUtil {

    public static Unsafe unsafe;
    private static long fieldOffset;
    private static UnsafeUtil instance = new UnsafeUtil();

    private Object obj;

    static {
        try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");

            unsafe = (Unsafe)f.get(null);
            fieldOffset = unsafe.objectFieldOffset(UnsafeUtil.class.getDeclaredField("obj"));
        } catch (Exception e) {
            throw new RuntimeException(e);

My vote goes to java.util.concurrent with its concurrent collections and flexible executors allowing among others thread pools, scheduled tasks and coordinated tasks. The DelayQueue is my personal favorite, where elements are made available after a specified delay.

java.util.Timer and TimerTask may safely be put to rest.

Also, not exactly hidden but in a different package from the other classes related to date and time. java.util.concurrent.TimeUnit is useful when converting between nanoseconds, microseconds, milliseconds and seconds.

It reads a lot better than the usual someValue * 1000 or someValue / 1000.

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.

As of Java 1.5, Java now has a much cleaner syntax for writing functions of variable arity. So, instead of just passing an array, now you can do the following

public void foo(String... bars) {
   for (String bar: bars)

bars is automatically converted to array of the specified type. Not a huge win, but a win nonetheless.