295
votes

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

2
  • 17
    Note that it's not always a great idea to use these hidden features; often times they are surprising and confusing to others reading your code. Nov 5, 2009 at 18:10
  • 1
    You (/someone) should probabbly sum up the answers neatly in the question body like the C# question.
    – ripper234
    Dec 10, 2009 at 19:34

100 Answers 100

432
votes

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.

16
  • 40
    Double-brace initialization... weird... I'd be wary of adopting that particular idiom too widely though, since it actually creates an anonymous subclass of the object, which could cause confusing equals/hashcode problems. java.util.concurrent is a truly great package.
    – MB.
    Sep 17, 2008 at 12:02
  • 6
    I have taught Java, and this is the very first time I've come across this syntax... which goes to show you never stop learning =8-)
    – Yuval
    Sep 23, 2008 at 8:48
  • 49
    Note that if you retain a reference to a collection initialized with this "double brace" idiom (or if we call it by its real name - annonymous class with initializer block), you implicitly hold a reference to the outer object which can cause nasty memory leaks. I'd recommend avoiding it altogether.
    – ddimitrov
    Oct 5, 2008 at 13:05
  • 51
    "Double-brace initialization" is a very euphemistic name for creating an anonymous inner class, glossing over what's really happening and making it sound as if inner classes were intended to be used this way. This is a pattern I'd prefer remain hidden.
    – erickson
    Oct 23, 2008 at 14:27
  • 11
    Almost, it is not really a static block but an "initializer block" which is different since it gets executed at a different time (see the link I put in the answer for more details) Mar 11, 2009 at 9:49
279
votes

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.

4
  • My favourite use for this is when you need a method that accepts an Appendable Charsequence. Apr 20, 2009 at 3:51
  • 5
    Is it possible to have an "OR" there instead of the &? Jun 16, 2009 at 18:37
  • 9
    @Grasper: No, OR (disjoint union) is not provided in that context. But you can use a disjoint union datatype like Either<A, B> instead. This type is the dual of a Pair<A, B> type. Look at the Functional Java library or the Scala core libraries for an example of such a datatype.
    – Apocalisp
    Jun 16, 2009 at 21:51
  • 5
    You should said that you MUST extends only one class and several interfaces -> public class Baz<T extends Clazz & Interface1 & InterfaceI... and not class Baz<T extends Clazz1 & ClazzI>
    – JohnJohnGa
    Oct 17, 2011 at 8:53
219
votes

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>(){{ 
  put("1","one"); 
  put("2","two");
}};
9
  • 38
    The advantage of this over an explicit method that needs to be called is that if someone adds a constructor later they don't need to remember to call init(); that will be done automatically. This can prevent errors by future programmers. Oct 10, 2008 at 15:45
  • 40
    Also, unlike an init() method, it can initialize final fields.
    – Darron
    Jan 7, 2009 at 18:45
  • 2
    What if you extend the class and instantiate various children? Will it still behave in the same manner? Jan 27, 2009 at 12:48
  • 12
    People often dis certifications (e.g. stackoverflow.com/questions/281100/281127#281127) and especially question their technical merits. But if more programmers here had studied for their SCJP, this would not be considered a "hidden feature" by so many. ;-)
    – Jonik
    Apr 21, 2009 at 8:46
  • 12
    I bet even "java in 24 hours" book has this "obvious feature". read more guys :)(
    – Özgür
    May 6, 2009 at 19:40
201
votes

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.

4
  • And it has a plugin (it is an netbeans thingie) that allows it to use Jconsole plugins. Quite nice. May 26, 2009 at 7:54
  • VisualVM is the best thing since sliced bread, really! Too bad it doesn't have all the features when running against JDK 1.5
    – sandos
    Feb 17, 2010 at 12:26
  • I find VisualVM slow or unusable in some circumstances. The commercial YourKit does not have this problem, but is unfortunately not free.
    – Roalt
    Sep 23, 2010 at 11:33
  • The more recent versions of Visual VM, from JDK 1.6.0_22 and later, are much improved. I would bet JDK1.7 has an even better version of it.
    – djangofan
    Aug 24, 2011 at 20:40
173
votes

Classpath wild cards since Java 6.

java -classpath ./lib/* so.Main

Instead of

java -classpath ./lib/log4j.jar:./lib/commons-codec.jar:./lib/commons-httpclient.jar:./lib/commons-collections.jar:./lib/myApp.jar so.Main

See http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html

156
votes

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

// code goes here

getmeout:{
    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? :)

18
  • 2
    Well, I would rather prefer to have an option to do it several ways. For example, I saw people using System.exit(1); in Servlet and EJB code, but that does not mean that we should remove System.exit(); from the JDK, right? Sep 8, 2008 at 10:25
  • 31
    Under some circumstances, within a nested loop construct, it can be useful to continue to the next iteration of an outer loop. This would be a reasonable use of this feature.
    – alasdairg
    Nov 8, 2008 at 18:57
  • 75
    What's especially unknown to many programmers (and probably just as well) is that you can actually label and break out of ANY old block. It doesn't have to be a loop-- you can just define some arbitrary block, give it a label, and use break with it. Apr 20, 2009 at 4:10
  • 27
    It is not a goto at all, it can only return to a prior iteration (ie: you cannot jump forward). This is the same mechanism that occurs when an iteration returns false. Saying java has goto is like saying any language whose compiler produces a JUMP instruction has a goto statement.
    – Zombies
    Oct 1, 2009 at 13:38
  • 4
    So you interview based on Java trivia rather than on aptitude to solve problems and think through designs. I'll make sure I never interview with your company. :) Aug 24, 2010 at 20:35
144
votes

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 {
    @Override
    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.

2
  • Can you provide an example usage? Sep 12, 2008 at 15:58
  • 24
    I use this a lot. clone() is a great example. It's supposed to return Object, which means you'd have to say e.g. (List)list.clone(). However if you declare as List clone(){...}, then the cast is unnecessary. Sep 14, 2008 at 15:04
142
votes

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 {
      return;
    }
  }

From http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html

6
  • 7
    It's nasty, but it's also kind of just a logical consequence of how finally works. The try/catch/finally flow control does what it's intended to do, but only within certain limits. Similarly, you have to be careful not to cause an exception inside a catch/finally block, or you'll also throw away the original exception. And if you do a System.exit() inside the try block, the finally block won't be called. If you break the normal flow, you break the normal flow... Apr 20, 2009 at 3:54
  • Don't use finally { return; } but just finally{ code without return}. This is logical, as finally is also intended to be executed when exceptions occurred, and the only possible meaning of a return as exception handler must be to ignore the exception and - indeed - return.
    – extraneon
    May 21, 2009 at 15:21
  • 21
    This seems like more of a "gotcha" than a hidden feature, though there are ways it could be used as one, using this method wouldn't be a good idea.
    – davenpcj
    Jun 3, 2009 at 20:00
  • Eclipse emits a warning if you do this. I'm with Eclipse. If you want to catch an exception... then catch an exception.
    – helios
    Mar 3, 2010 at 15:24
  • That's what you pay for dirty code that returns from middle of method. But still a nice example. Jun 22, 2010 at 12:21
140
votes

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 )
{
    ...
}
3
  • 9
    It's a shame that this is such a little-known feature. I've seen a lot of code similar to the first block of code. Dec 24, 2009 at 16:20
  • 4
    That's because Java has a special (hidden) null type that you do not see, nor can reference. Jul 1, 2011 at 4:14
  • What's worse is checking for null before freeing or deleteing in C/C++. Such a fundamental concept. Feb 4, 2012 at 23:04
134
votes

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.

11
  • 20
    Really awesome feature actually--makes enums OO and solves a lot of initialization problems in a very clean way.
    – Bill K
    Oct 6, 2008 at 18:00
  • 5
    Enum as singleton? Enum with only one value? Nov 13, 2008 at 0:01
  • 6
    Georgy: Singleton is one instance of the object, not an object with one value.
    – dshaw
    Nov 17, 2008 at 22:43
  • 20
    @Georgy: see also Item 3 in Joshua Bloch's Effective Java (2nd ed); "While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."
    – Jonik
    Apr 21, 2009 at 8:57
  • 3
    Minor nitpick: mAge should be final. There's rarely a reason for non-final felds in enums. Oct 6, 2010 at 8:25
121
votes

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

Collections.<String,Integer>emptyMap()
5
  • 10
    And by god is it ugly and confusing. And irrelevant to type safety. Sep 16, 2008 at 12:21
  • 8
    I love this. It makes your code a bit more explicit and as such more clear for the poor sod who will have to maintain it in a year or two.
    – extraneon
    May 21, 2009 at 15:30
  • 6
    This is actually very useful in situations where you have declared a static generic method such as public static <T> T foo(T t). You can then make calls to Class.<Type>foo(t);
    – Finbarr
    May 13, 2010 at 8:20
  • For some reason this doesn't seem to work with statically imported methods.. I wonder why.
    – oksayt
    Apr 25, 2011 at 17:30
  • This is especially useful when using ternary ifs with a return. For example return set1.equals(set2) ? new ArrayList<String>(set1) : Collections.<String>emptyList(). It also useful for some method invocations where a simple Collections.emptyMap() would give a compile error. Jun 30, 2011 at 20:30
112
votes

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;
      }
   },
   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 {

https://github.com/peter-lawrey/Java-Thread-Affinity/blob/master/src/main/java/vanilla/java/affinity/AffinityStrategies.java

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

2
  • 12
    @Arian this isn't madness. THIS. IS. JAVAAAAAAHHHH!
    – salezica
    Oct 13, 2011 at 12:45
  • 1
    WHAAAAAT no, I'm with Adrian. This is not Java. This is madness. I'm dying to use this.
    – salezica
    Mar 5, 2012 at 9:12
104
votes

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)
      System.out.println(bar);
}

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

3
  • 23
    The important thing about this is when calling the method, you can write: foo("first","second","third") Mar 25, 2009 at 20:03
  • 9
    so the old hello world can be rewritten; public static void main(String... args) { System.out.println("Hello World!"); }
    – Karussell
    Jan 22, 2010 at 21:56
  • @Karussell Maybe, but it would seem the arguments are irrelevant :p Oct 2, 2011 at 22:41
93
votes

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

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

unix: kill -3 PID

5
  • 15
    Also ctrl-\ in Unix. Or use jstack from the JDK. Sep 17, 2008 at 14:53
  • 9
    Thanks, you just taught me my keyboard has a Break key.
    – Amy B
    Aug 18, 2010 at 22:53
  • 2
    On windows, CTRL-BREAK only works if you have the process running in the current console window. You can use JAVA_HOME/bin/jstack.exe instead. Just provide it with the Windows process id. Aug 24, 2010 at 20:40
  • I thought it was kill -SIGQUIT Jul 1, 2011 at 4:14
  • @Nick, yes SIGQUIT is usually signal #3. Jul 14, 2011 at 15:32
89
votes

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"){{ 
    setBackground(Color.black);
    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"){{ 
                    setBackground(Color.black);
                    setForeground( Color.white);
                }});

                add( new JButton("Ok"){{
                    addActionListener( new ActionListener(){
                        public void actionPerformed( ActionEvent ae ){
                            System.out.println("Button pushed");
                        }
                     });
                 }});
        }});
    }};
10
  • Somehow, it is a bit as if "with" keyword (functionality, actually) have been added to Java. Can be very handy, recently I grunted because init of arrays wasn't available for Collections. Thanks!
    – PhiLho
    Dec 13, 2008 at 9:06
  • 15
    There is one side-effect of using this, though. Anonymous objects get created, which may not be fine always.
    – amit
    Feb 10, 2009 at 8:14
  • 17
    Although after looking at it more, I have to say I'm strangely attracted to the natural nesting this provides, even the "Abused" version.
    – Bill K
    Jun 11, 2009 at 21:32
  • 4
    Yep - I quite like the 'abused' version, I think that's really very clear and readable, but perhaps that's just me.
    – barryred
    Aug 5, 2010 at 15:55
  • 3
    Absolutely agree, the hierarchy of the code reflecting the hierarchy of the gui is a huge improvement over a sequence of method calls.
    – opsb
    Oct 29, 2010 at 9:08
88
votes

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.

1
  • 10
    Dynamic proxies are a great reason to choose to write a Foo interface and use that everywhere, with a default "FooImpl" class. It may seem ugly at first ("Why not just have a class called Foo?") but the benefits in terms future flexibility and mock-ability for unit tests are handy. While there are ways to also do it for non-interfaces, they typically require extra stuff like cblib.
    – Darien
    Apr 21, 2010 at 19:57
81
votes

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;
}
7
  • That's surprising. Can one fairly say, "The value of a final variable can be set once", no matter where the set occurs? Feb 4, 2009 at 19:12
  • 29
    Yes, but more strongly: "The value of a final variable must be set once" Feb 4, 2009 at 22:15
  • 6
    +1 Agree, this is another valuable tool for spotting errors at compile time, and one that programmers seem shy to use for some reason. Note that because from Java 5 onwards, 'final' also has thread-safety implications, being able to set a final variable during the constructor is invaluable. Apr 20, 2009 at 4:16
  • 4
    Though for this specific method, I'd just use multiple returns. In fact, in most cases where this is applicable, I'd probably refactor it into a separate method and use multiple returns.
    – ripper234
    Nov 17, 2009 at 21:31
  • I love this! I deleted the final keyword always because I thought it will fail. thanks! Jan 25, 2010 at 10:20
62
votes

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.

7
  • 18
    No. It's actually not a very good VM. It was solely designed to run JAVA. Typeless dynamic and functional languages don't work well with it. Of you want to use a VM you should use .NET/Mono. That was designed to work with EVERY language...
    – Hades32
    Jun 22, 2009 at 17:33
  • 14
    Actually the JVM is solely designed to run Java Bytecodes. You can compile most modern languages to Java Bytecode. About the only things Java Bytecode is lacking in is dynamic language support, pointers, and tail recursion support.
    – mcjabberz
    Sep 18, 2009 at 15:43
  • 12
    @Hades32: actually the .NET VM is pretty similar to the JVM. It only got support for dynamic languages relatively recently (with the DLR) and Java 7 is about to get that support as well. And the classical "EVERY language" of .NET (C#, Visual Basic.NET, ...) all have pretty much exactly the same feature set. Nov 27, 2009 at 8:12
  • 13
    JVM doesn't support generics, while the .NET VM does. JVM is nowhere near the best.
    – Blindy
    Nov 27, 2009 at 8:52
  • 3
    Not to discount the complaints about specific language features not directly supported by the JVM... but I tend to think stability, cross-platform consistency, and good performance are far and above the reasons the JVM gets extra points. I've been working with server-side Java for many years now on many platforms (including AS/400) and have been able to pretty much forget about it entirely -- the bugs are pretty much always in code I can fix, and it simply doesn't crash.
    – Rob Whelan
    Jan 8, 2012 at 20:22
58
votes

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) {
    System.out.println(s);
  }
}.foo("Hello");
4
  • @Vuntic - It does allow you to define a simple class within the context that it is needed. Jul 12, 2010 at 16:49
  • 1
    @Chaos, But why? Got an actual example where it is useful? Dec 3, 2010 at 14:19
  • 10
    @Wouter - In that case, the method which is called on the anonymous object (start()) is not actually defined in the subclass...
    – Axel
    Aug 2, 2011 at 8:35
  • Actually, this is a very useful feature if you extend a base class that does some needed setup, calls the method you write, and then does teardown. Kick the thing off by calling a method in the base class (which I probably wouldn't give the same name). There's an example use (not definition) here
    – AmigoNico
    Jan 8, 2012 at 6:02
56
votes

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);
2
  • 15
    you want to wrap the returned list with a List constructor otherwise ints will be fixed size (since it is backed by the array)
    – KitsuneYMG
    Aug 4, 2009 at 13:39
  • 2
    The Arrays.asList has the unusual feature that you can set() elements but not add() or remove(). So I usually wrap it in a new ArrayList(...) or in a Collections.unmodifiableList(...), depending on whether I want the list modifiable or not. Dec 3, 2010 at 22:31
53
votes

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;
}
}
3
  • 4
    That's only necessary if you've shadowed the name (in your case, with the method parameter name). If you'd called the argument something else, then you could directly access the sortAscending member variable of Container class without using 'this'.
    – sk.
    Feb 4, 2009 at 17:12
  • 7
    It is still useful to have a reference to the enclosing class, eg. if you need to pass it to some method or construtor.
    – PhiLho
    Feb 14, 2009 at 19:13
  • Often used in Android layout development, in order to get the Context from, say, the listener of a button, with MyActivity.this.
    – espinchi
    Apr 29, 2011 at 17:19
52
votes

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!");
    http://Phi.Lho.free.fr

    System.exit(0);
  }
}

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!

1
46
votes

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");
            f.setAccessible(true);

            unsafe = (Unsafe)f.get(null);
            fieldOffset = unsafe.objectFieldOffset(UnsafeUtil.class.getDeclaredField("obj"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    };
}
3
  • 20
    that is a sun.* API which isn't really part of the Java language per se
    – DW.
    Mar 5, 2009 at 2:53
  • There are a number of other curious methods on Unsafe like creating an object without calling a constructor, malloc/realloc/free style methods. Jul 22, 2010 at 21:11
  • I love esspecially the primitive getters and setters on memory locations, like putDouble(long address, double d).
    – Daniel
    Feb 26, 2011 at 22:10
42
votes

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

1
  • 1
    Most likely your window manager has something bound to that key. Gnome doesn't bind to it, so I'm assuming you're running KDE which binds it to 'switch to desktop 13'. You can change it by going to Control panel, Regional, Keyboard Shortcuts and removing the mapping for Shift-Ctrl-F1 Jun 2, 2010 at 14:40
40
votes

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

(Explanation)

0
38
votes

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.

1
  • Recently discovered CountDownLatch and CyclicBarrier -- so useful!
    – Raphael
    Mar 1, 2012 at 10:06
37
votes

Language-level assert keyword.

5
  • 19
    The trouble with assert is that it needs to be switched on during runtime.
    – extraneon
    May 21, 2009 at 15:42
  • 10
    But if it's disabled it's like it's not there. You can add as many asserts as you want in your code and you won't have any performance penalty if they're disabled. Aug 9, 2009 at 5:15
  • 5
    I believe that’s a good thing about assert: it can be turned off without penalty.
    – andref
    Jul 11, 2010 at 17:41
  • the problem is, if you accidentally implemented a side effect in an assert, you've got to turn on assertion for ur program to work...
    – Chii
    Oct 12, 2010 at 11:15
  • To detect if asserts are on, you can use { boolean assertsOn = false; assert assertsOn = true; if (assertsOn) { /* complex verification */ } }. This also allows to log or throw exception if state of assert is not the expected.
    – fernacolo
    Jun 23, 2011 at 18:26
37
votes

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

36
votes

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) {
  System.out.println(foo.toString());
}

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

7
  • 30
    I think using i here is super-confusing, as most people expect i to be an index and not the array element.
    – cdmckay
    Feb 23, 2009 at 7:28
  • So... int sum(int[] array) { int result = 0; for(int element : array) { result += element; } return result; }
    – Drew
    Mar 10, 2009 at 23:27
  • 28
    The only thing that drives me nuts about this is that it seems like it would be really really easy to create a keyword for accessing the loop count value, but you can't. If I want to loop over two arrays and make changes to a second based on values in the first I'm forced to use the old syntax because I have no offset into the second array.
    – Jherico
    May 19, 2009 at 21:34
  • 6
    It's a shame it doesn't also work with Enumerations, like those used in JNDI. It's back to iterators there.
    – extraneon
    May 21, 2009 at 15:32
  • 3
    @extraneon: take a look at Collections.list(Enumeration<T> e). That should help with iterating enumerations in the foreach loop. Mar 24, 2010 at 23:49
34
votes

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

2
  • 2
    not quite. at some point, you need to be specific: Executors.newSingleThreadExecutor().submit(new Callable<Void>() {..}) -- you can't instantiate a new Callable<?>(), you need to specify an explicit type -- thus, it's an alternative to Callable<Object>. Jun 17, 2009 at 14:59
  • 4
    Void is more specific than Object as Void can only be null, Object can be anything. Jul 22, 2010 at 21:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.