views:

41518

answers:

103

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

+27  A: 

Language-level assert keyword.

Mark Cidade
The trouble with assert is that it needs to be switched on during runtime.
extraneon
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.
Ravi Wallau
I believe that’s a _good_ thing about assert: it can be turned off without penalty.
andref
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
+13  A: 

I really like the rewritten Threading API from Java 1.6. Callables are great. They are basically threads with a return value.

Mo
When compared to the older stuff is simple
Allain Lalonde
Callables are Runnables with a return value, not threads.
Tom
Examples, please?
neu242
Basically there are ExecutorServices, to which you can submit Callables. When you submit a Callable to an ExecutorService, you get back a Future, which has a blocking call to get the result of the Callable (or you can ask it if there is a result yet, non-blocking).
Adam Jaskiewicz
An ExecutorService is some way of running Callables (and Runnables). It might be a single background thread, it might be backed by a thread pool, it might even run the tasks sequentially in the current thread. Depends on the implementation.
Adam Jaskiewicz
There's also a CompletionService that can have Callables submitted to it, and the results queue up for consumption as they finish.
Adam Jaskiewicz
It's there since 1.5
KARASZI István
+17  A: 

static imports to "enhance" the language, so you can do nice literal things in type safe ways:

List<String> ls = List("a", "b", "c");

(can also do with maps, arrays, sets).

http://gleichmann.wordpress.com/2008/01/13/building-your-own-literals-in-java-lists-and-arrays/

Taking it further:

List<Map<String, String>> data = List(Map( o("name", "michael"), o("sex", "male")));
Michael Neale
It's really too bad this type of functionality isn't directly in the collections API.
Chris Mazzola
this isn't part of the language; the author in the link defines the "List" method to create a list
kdgregory
This is a method like: ... public static <T> List<T> List(T...elems){ return Arrays.asList( elems ); } You can also write: List<String> myList = new ArrayList<String>(Arrays.asList("One", "Two", "Three")); //as mentioned in another post
xgMz
Isn't this the Factory design pattern? Very usefull of course, especially with varargs.
extraneon
static import java.util.Arrays; List<String> names = asList("jim", "john")
opsb
+40  A: 

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.

Mo
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
Java 7 will have new bytecodes to support dynamic languages.
Michael Borgwardt
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
@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.
Joachim Sauer
JVM doesn't support generics, while the .NET VM does. JVM is nowhere near the best.
Blindy
+244  A: 

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.

Boris Terzic
It's too bad my IDE (NetBeans) formats them horribly when it's auto-formatting.
Allain Lalonde
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
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
Note that the compiler generates an AnonymousInnerClass to implement Double Brace Initialization, therefore it only works for non-final classes. Which is a shame, since literal initializations are often inteneded as constants.
Chris Noe
The double brace initialization is really interesting.
Steve g
Double brace took me by surprise too, thanks for the heads up
qualidafial
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
"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
I have to admit this is the first time I've seen double braces in Java. Great tip!!!
Stephane Grenier
To make sure I understand, the double brace creates an anonymous inner class, then creates a static block inside it, which then lets you execute methods from a static context. Correct?
Drew
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)
Boris Terzic
This is probably OK if used occasionally, but if you encourage everyone to do it, your project will get littered with lots of spurious anonymous classes before you know it. For example, going via Arrays.asList() for initialising a hash set is generally preferable.
Neil Coffey
Bonus points for the link to C2.
Paul Morie
This is also known as "crazybob's contraption." Though I can't find the origin of that name, google finds multiple uses.
Chadwick
Although the double brace thing is interesting--I'd say it's really not worth it. At the very least you are mixing data in with code--always a bad idea. To keep size down, an even smaller version of their example would be: String initial = new String[]{"XZ13s","AB21/X","YYLEX","AR2D"}; then just use initial in a loop of "adds". This has the added advantage that your data is 95% extracted and would then be trivial to move out of your code completely. Creating String arrays is a very light syntax and great for keeping your code and data from getting too intimate.
Bill K
Don't like it, I find it a bit horrendous to create an an anonymous subclass for no reason :)
Chris Dennett
"Double Brace Initialization" is really three separate concepts. They are unrelated, except for having similar syntax, so I'm not sure why we've invented a term that covers all three. Developers should understand that they are code constructs with different uses. They are: anonymous class declaration: new Object() {}, the initializer block: class MyObject { int x; { x=0; /*initializer block doesn't have to be static*/ } }, and array literal notation: new Object[]{ "One", "Two", "Three" }. I wouldn't call any of these an anti-pattern, though use of anonymous classes should be limited.
RMorrisey
+11  A: 

Not really a feature, but it makes me chuckle that goto is a reserved word that does nothing except prompting javac to poke you in the eye. Just to remind you that you are in OO-land now.

serg10
http://stackoverflow.com/questions/15496/hidden-features-of-java#answer-39433:-)
Nivas
Is there some relationship between Object Oriented programming and not using "goto"?
Adrian Pronk
+20  A: 

As a starter I really appreciate the JConsole monitoring software in Java 6, it has solved a couple of problems for me already and I keep on finding new uses for it.

Apparently the JConsole was there already in Java 5 but I reckon it is improved now and at least working much more stable as of now.

JConsole in Java 5: JConsole in Java 5

JConsole in Java 6: JConsole in Java 6

And while you are at it, have a good look at the other tools in the series: Java 6 troubleshooting tools

pp
JConsole will be replaced vy VisualVM in future versions (6u10 maybe?)
Tom
Sure, JConsole will be replaced or rather refined, already from 6u7 i think. But many still use the older versions of suns JVM and thus needs the JConsole. I have still not found anything supporting the theory that JVisualVM will support older versions of the JDKs.
pp
+10  A: 

It's not exactly hidden, but reflection is incredibly useful and powerful. It is great to use a simple Class.forName("...").newInstance() where the class type is configurable. It's easy to write this sort of factory implementation.

John Meagher
I use reflection all the time to do things like <T> T[] filterItems(T[])which you can then call with items = filterItems(items);The method definition is a bit uglier, but it really makes client code easier to read.
Marcus Downing
+102  A: 

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.

serg10
Can you provide an example usage?
Allain Lalonde
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.
Jason Cohen
Jason, great point. and very useful.
Nivas
I didn't know this was a new feature in 1.5. I use it a lot also.
RMorrisey
+5  A: 

Functors are pretty cool. They are pretty close to a function pointer, which everyone is usually quick to say is impossible in Java.

Functors in Java

Brad Barker
Not impossible, merely impossibly verbose.
Pete Kirkham
Isnt this a feature of opps than java specific??
Ravisha
+95  A: 

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

Georgy Bolyuba
I'd almost hope people not know about this feature. Far preferable that they organise their code into smaller, more meaningful methods and simply use `return`, in most cases. There is a great furore at the moment around this language construct being added to PHP6.
Cheekysoft
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?
Georgy Bolyuba
I agree that it should be allowed in the language even if it's not used often. I can't recall a single instance when I have used it but I have seen both sides of the argument for it's use. Better to have it and not use it than need it and not have it.
martinatime
Eeew... it scares the sh*t out of me to think what a cowboy developer could do with such a weapon at hand... :-S
Manrico Corazzi
I've found one instance where this was useful, do to weirdness of the flow. In the end I just redesigned the whole thing to not need it and it was simpler. I decided to abide by the "psychopath who knows where you live" rule..
firebird84
...considered harmful.
Andreas Petersson
Does this need to be a block? I was under the impression it just labels the for loop.
Jack Leow
It can be any block
Georgy Bolyuba
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
in case of several nested loops, yeah. But I would rather rewrite the code.
Georgy Bolyuba
I used that in http://stackoverflow.com/questions/288200/prime-number-calculation-fun#288669 First time I used it, seemed natural... :-)
PhiLho
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.
Neil Coffey
Holy cow. I had absolutely no idea that I could do that.
CaptainAwesomePants
What a surprise I had no idea too. I like spaghetti but not in code, I'm not sure if I'd use in dangerous knowledge in the future
victor hugo
Hmmm, goto. Long time no see. Inspiration becons... Eclipse, here I come!
extraneon
Now that feature is an excuse to put goto back!
Joshua
Wow, I never knew that! That would be useful. Thanks!
PCBEEF
I really hope you are joking.
Georgy Bolyuba
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
Wow! This makes Java's nasty exception mechanism look sane!
Kristian B
This is a great feature I use now and then to avoid nested `if` statemens and to shorten some iterative constructs. This is not a `goto`; just because you (people) don't know it doesn't mean it's wrong to use. All those "scared" should go read some book on Java.
Ondra Žižka
I think the only time I would use this construct would be to translate assembly code to java on a really tight deadline.
RMorrisey
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. :)
Javid Jamae
So, you comment by stretching a point and/or making some far going generalization and/or assumptions. I'll make sure never to read your comments again. :)
Georgy Bolyuba
+11  A: 

I was aware that Java 6 included scripting support, but I just recently discovered jrunscript, which can interpret and run JavaScript (and, one presumes, other scripting languages such as Groovy) interactively, sort of like the Python shell or irb in Ruby

yalestar
+62  A: 

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.

jodonnell
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
+147  A: 

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.

Apocalisp
My favourite use for this is when you need a method that accepts an Appendable Charsequence.
Neil Coffey
Is it one ampersand or two? Your examples are different.
PanCrit
Good catch, PanCrit. It's one ampersand.
Apocalisp
Grasper
@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
+4  A: 

I know this was added in release 1.5 but the new enum type is a great feature. Not having to use the old "int enum pattern" has greatly helped a bunch of my code. Check out JLS 8.9 for the sweet gravy on your potatoes!

Matt Cummings
Most "old school" Java guys never bother to start using this feature, but I agree it's great.
Allain Lalonde
+6  A: 

final for instance variables:

Really useful for multi-threading code and it makes it a lot easier to argue about the instance state and correctness. Haven't seen it a lot in industry context and often not thought in java classes.


static {something;}:

Used to initialize static members (also I prefer a static method to do it (because it has a name). Not thought.

dmeister
Yeah, a static method will also allow you to deal nicely with exceptions but when you use the static block you have no choice but to catch (and not do any appropriate action).
Graham Edgecombe
+137  A: 

I was surprised by instance initializers the other day:

public class Foo {
    public Foo() { System.out.println("constructor called"); }

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

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

Executing the following code

new Foo();
new Foo();

will display:

static initializer called
instance initializer called
constructor called
instance initializer called
constructor called

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

David Carlson
It'd probably be more legible to have a method that all your constructors invoked, or to have all the constructors invoke a root one this(...) as opposed to super(...)
Allain Lalonde
It's good to know that checked exceptions thrown in anonymous initializers need to be declared by the constructors. Static initializers cannot throw checked exceptions.
Tom
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.
Mr. Shiny and New
Good Point Mr Shiny
Allain Lalonde
Also, unlike an init() method, it can initialize final fields.
Darron
What if you extend the class and instantiate various children? Will it still behave in the same manner?
Kezzer
People often dis certifications (e.g. http://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
I bet even "java in 24 hours" book has this "obvious feature". read more guys :)(
Comptrol
+5  A: 

Joshua Bloch's new Effective Java is a good resource.

warsze
Great book, but it doesn't really deal so much with hidden features.
James McMahon
+83  A: 

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.

Adrian Mouat
Really awesome feature actually--makes enums OO and solves a lot of initialization problems in a very clean way.
Bill K
Enums are also great for singletons because of this.
Chii
Enum as singleton? Enum with only one value?
Georgy Bolyuba
Georgy: Singleton is one instance of the object, not an object with one value.
dshaw
This is really handy if you want enumerators relative to a value. So in the example, perhaps you could initialise Cats with a specified age value then have FELIX(2 + age), that way, Felix's age will be relative to the instance of the Cats age.
Kezzer
Enums are so OO that you could even add a public void setAge(int age) {this.mAge=afe} ... and it works !!
Olivier
@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
sadly not allowed in C#...
CrazyJugglerDrummer
Minor nitpick: `mAge` should be final. There's rarely a reason for non-final felds in enums.
Joachim Sauer
+23  A: 

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

binil
+11  A: 

Self-bound generics:

class SelfBounded<T extends SelfBounded<T>> {
}

http://www.artima.com/weblogs/viewpost.jsp?thread=136394

see also the cope's crtp: http://www.artima.com/weblogs/viewpost.jsp?thread=133275
Ray Tayek
+94  A: 

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.

Kevin Wong
Dude! That rocks!!
Ogre Psalm33
And it has a plugin (it is an netbeans thingie) that allows it to use Jconsole plugins. Quite nice.
Thorbjørn Ravn Andersen
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
more info on VisualVM: https://visualvm.dev.java.net/
ManBugra
+1: This ought to be more widely known.
Donal Fellows
I find VisualVM slow or unusable in some circumstances. The commercial YourKit does not have this problem, but is unfortunately not free.
Roalt
+73  A: 

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

Collections.<String,Integer>emptyMap()
Kevin Wong
And by god is it ugly and confusing. And irrelevant to type safety.
broady
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
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
+14  A: 

It took them long enough to add support for this,

System Tray

Andrew
+36  A: 

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);
Bruno De Fraine
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
+6  A: 

Some control-flow tricks, finally around a return statement:

int getCount() { 
  try { return 1; }
  finally { System.out.println("Bye!"); }
}

The rules for definite assignment will check that a final variable is always assigned through a simple control-flow analysis:

final int foo;
if(...)
  foo = 1;
else
  throw new Exception();
foo+1;
Bruno De Fraine
+6  A: 

JVisualVM from the bin directory in the JDK distribution. Monitoring and even profiling any java application, even one you didn't launch with any special parameters. Only in recent versions of the Java 6SE JDK.

Bill Michell
_Sun_ Java 6. Doesn't work with IBM Java.
Thorbjørn Ravn Andersen
If you're using Spring to tool up your annotated JMX beans to work with jconsole and jvisualvm, you *need* to manually start the management interface rather than relying on the default VM-created one. If you don't, you'll run into problems with the presence of multiple clashing “singletons” and your JMX beans will neatly end up in the wrong one…
Donal Fellows
+82  A: 

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

James A. N. Stauffer
That's scary... nice one!
Torsten Marek
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...
Neil Coffey
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
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
Say what??? What's the rational behind this "feature"??
ripper234
+1 to the good-to-know answer
Jon
Eclipse emits a warning if you do this. I'm with Eclipse. If you want to catch an exception... then catch an exception.
helios
That's what you pay for dirty code that returns from middle of method. But still a nice example.
binary_runner
+27  A: 

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

18Rabbit
I think using `i` here is super-confusing, as most people expect i to be an index and not the array element.
cdmckay
So...int sum(int[] array) {int result = 0;for(int element : array) {result += element;}return result;}
Drew
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
It's a shame it doesn't also work with Enumerations, like those used in JNDI. It's back to iterators there.
extraneon
@extraneon: take a look at Collections.list(Enumeration<T> e). That should help with iterating enumerations in the foreach loop.
deepc
The only possible problem with this is that it uses the List's `Iterator`, and any modification to the list within the loop will throw `ConcurrentModificationException`.
Finbarr
+5  A: 

"const" is a keyword, but you can't use it.

int const = 1;   // "not a statement"
const int i = 1; // "illegal start of expression"

I guess the compiler writers thought it might be used in the future and they'd better keep it reserved.

Michael Myers
hidden feature? how so?
Steve McLeod
Not exactly a "feature", but definitely "hidden".
Michael Myers
hehe a non-feature!
Chii
Not just a non-feature, an anti-feature! (I also didn't mention that `goto` is the same--reserved but unimplemented).
Michael Myers
+20  A: 

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!

PhiLho
This one is in <a href="http://www.javapuzzlers.com/">Java Puzzlers</a>.
cdmckay
neat, a label with a comment :)
Thorbjørn Ravn Andersen
+52  A: 

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

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

unix: kill -3 PID

Chris Mazzola
Also ctrl-\ in Unix. Or use jstack from the JDK.
Tom Hawtin - tackline
Or use jvisualvm.
JesperE
Thanks, you just taught me my keyboard has a `Break` key.
Coronatus
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.
Javid Jamae
+4  A: 

The power you can have over the garbage collector and how it manages object collection is very powerful, especially for long-running and time-sensitive applications. It starts with weak, soft, and phantom references in the java.lang.ref package. Take a look at those, especially for building caches (there is a java.util.WeakHashMap already). Now dig a little deeper into the ReferenceQueue and you'll start having even more control. Finally grab the docs on the garbage collector itself and you'll be able to control how often it runs, sizes of different collection areas, and the types of algorithms used (for Java 5 see http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html).

mpresley
`WeakHashMap` is *not* suitable for building caches.
Bombe
+33  A: 

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;
}
}
Tahir Akhtar
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
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
I use this all the time :)
Chris Dennett
+32  A: 

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);
     }
    };
}
Das
that is a sun.* API which isn't really part of the Java language per se
DW
There are a number of other curious methods on Unsafe like creating an object without calling a constructor, malloc/realloc/free style methods.
Peter Lawrey
+3  A: 

Since no one else has said it yet (I Think) my favorite feature is Auto boxing!

public class Example
{
    public static void main(String[] Args)
    {
         int a = 5;
         Integer b = a; // Box!
         System.out.println("A : " + a);
         System.out.println("B : " + b);
    }
}
I think the question is about hidden features, not favourite features. I'm guessing autoboxing is pretty well known to anyone who uses 1.5 or later.
Andrew Swan
Yes, but because of performance it's better to use valueOf.
Trick
+4  A: 

How about Properties files in your choice of encodings? Used to be, when you loaded your Properties, you provided an InputStream and the load() method decoded it as ISO-8859-1. You could actually store the file in some other encoding, but you had to use a disgusting hack like this after loading to properly decode the data:

String realProp = new String(prop.getBytes("ISO-8859-1"), "UTF-8");

But, as of JDK 1.6, there's a load() method that takes a Reader instead of an InputStream, which means you can use the correct encoding from the beginning (there's also a store() method that takes a Writer). This seems like a pretty big deal to me, but it appears to have been snuck into the JDK with no fanfare at all. I only stumbled upon it a few weeks ago, and a quick Google search turned up just one passing mention of it.

Alan Moore
+17  A: 

If you do a lot of JavaBean development and work with property change support, you generally wind up writing a lot of setters like this:

public void setFoo(Foo aFoo){
  Foo old = this.foo;
  this.foo = aFoo;
  changeSupport.firePropertyChange("foo", old, aFoo);
}

I recently stumbled across a blog that suggested a more terse implementation of this that makes the code a lot easier to write:

public void setFoo(Foo aFoo){
  changeSupport.firePropertyChange("foo", this.foo, this.foo = aFoo);
}

It actually simplified things to the point where I was able to adjust the setter template in Eclipse so the method gets created automatically.

Kevin Day
Is the order of execution for arguments well-defined in Java? Otherwise, this could potentially generate a mess.
Konrad Rudolph
It is well defined, but not generally well understood. This will technically work, but is clearly confusing.
Heath Borders
Yes - order or execution of arguments is extremely well defined. I'm not sure that I agree that this is more confusing than having 3 lines of junk code in every single setter in every single JavaBean - much better to keep the focus on the code you want to write instead of this type of boilerplate!
Kevin Day
Coma order of execution is very well defined. Has to be left to right, always.
Bill K
I don't see why the shorter version is any easier to create automatically than the longer one.
Jason Orendorff
Jason - fair 'nough - code generation can do it either way. That is kinda the point of code generation I guess ;-) Still a lot easier to read the code with reduced boilerplate (the presence of the getter and setter at all is still a huge amount of boilerplate, but that's a discussion for another day)
Kevin Day
You can use project lombok for this.
Alfred
+1 for Lombok: it can totally eliminate such code.
A. Ionescu
+4  A: 

String Parameterised Class Factory.

Class.forName( className ).newInstance();

Load a resource (property file, xml, xslt, image etc) from deployment jar file.

this.getClass().getClassLoader().getResourceAsStream( ... ) ;
Martin Spamer
+7  A: 

Something that really surprised me was the custom serialization mechanism.

While these methods are private!!, they are "mysteriously" called by the JVM during object serialization.

private void writeObject(ObjectOutputStream out) throws IOException;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

This way you can create your own custom serialization to make it more "whatever" (safe, fast, rare, easy etc. )

This is something that really should be considering if a lot of information has to be passed through nodes. The serialization mechanism may be changed to send the half of data. There are many times when the bottlenecks are not in the platform, but in the amount of that sent trough the wire, may save you thousands of dlls in hardware.

Here is an article. http://java.sun.com/developer/technicalArticles/Programming/serialization/

OscarRyz
This is also useful for custom serialization for objects with non-Serializable members.
Jorn
It’s only surprising if you fail to read the documentation.
Bombe
+10  A: 

You can declare a class in a method:

public Foo foo(String in) {
    class FooFormat extends Format {
        public Object parse(String s, ParsePosition pp) { // parse stuff }
    }
    return (Foo) new FooFormat().parse(in);

}
oxbow_lakes
You could have also just go new Format() {, instead of declaring the FooFormat class
Pyrolistical
Anonymous classes are overrated. Try debugging one sometime, or supporting one in the field, and you'll see what I mean. Once you lose line numbers in a release build, they're *very* hard to track.
TREE
and they are called local classes :) http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#247766
Comptrol
I prefer to tame anonymous classes by having them call back into the main object to do their work; the anonymous class is just an adapter and so is easy to get right.
Donal Fellows
@Donal - I use this with UI code a lot. It's worth saying that this design is bad from the perspective of refactoring though. You could extract a "top-level" class and find that it's logic was implemented by another class entirely!
oxbow_lakes
@oxbow: I don't entirely get your point. The only thing in my inner class is a call to a (usually non-public) method on the outer class. While yes, in theory it could be quite surprising that this is going on, it's pretty easy to see in practice as it is *just* a call with no exception handling.
Donal Fellows
+5  A: 

Annotation Processing API from Java 6 looks very perspective for code generation and static code verification.

+42  A: 

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;
}
Allain Lalonde
That's surprising. Can one fairly say, "The value of a final variable can be set once", no matter where the set occurs?
David
Yes, but more strongly: "The value of a final variable must be set once"
Allain Lalonde
+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.
Neil Coffey
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
I love this! I deleted the final keyword always because I thought it will fail. thanks!
KARASZI István
This is generally a bit of a code smell. As mentioned above it should be refactored to use guard closes(with multiple returns). If a block like this exists as only part of a method it should be extracted to a new method with multiple returns.
opsb
+2  A: 

Some years ago when I had to do Java (1.4.x) I wanted an eval() method and Suns javac is (was?) written in Java so it was just to link tools.jar and use that with some glue-code around it.

+19  A: 

Java processing does a neat trick on variable definition if you do not use a default initializer.

{
   int x;

   if(whatever)
      x=1;

   if(x == 1)
      ...
}

This will give you an error at compile time that you have a path where X isn't properly defined. This has helped me a few times, and I've taken to considering default initialization like these:

int x=0;
String s=null;

to be a bad pattern since it blocks this helpful checking.

That said, sometimes it's difficult to get around--I have had to go back and edit in the =null when it made sense as a default, but I never put it in on the first pass any more.

Bill K
+1 Agreed-- for some reason some people find it "confusing" not to supply an initial value for a variable, as though they think the compiler is secretly going to pick a random number or something. But as you rightly say, it's a valuable tool to spot certain errors at compile-time.
Neil Coffey
That's because in the C universe, uninitialized pointers were the bane of existence - though if I remember correctly, in the C++ universe, pointers were automatically initialized to null if allocated on the stack.
Chris Kaminski
Yeah, that's why it's worth pointing out that it's no longer really a good idea and in fact somewhat counter-productive.
Bill K
Use final wherever possible for additional checks.
Wouter Lievens
A: 

These answers almost could be a website in themselves... Hidden Java... Hmmm...

Steve McLeod
+4  A: 

You can access final local variables and parameters in initialization blocks and methods of local classes. Consider this:

    final String foo = "42";
    new Thread() {
        public void run() {
             dowhatever(foo);
        }
    }.start();

A bit like a closure, isn't it?

hstoerr
Of course, because you can't access non-finals.
Adeel Ansari
I knew that you can't acces non-finals, but I was surprised that you *can* access finals.
hstoerr
It *is* a closure!
Nat
+12  A: 

The value of:

new URL("http://www.yahoo.com").equals(new URL("http://209.191.93.52"))

is true.

(From Java Puzzlers)

Jack Leow
Only if you are connected to the Internet. If it can't resolve the address, it will return false, and therefore the URL class breaks the equals() contract. Better use the URI class in java.net.
Jorn
+55  A: 

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");
                        }
                     });
                 }});
        }});
    }};
Jack Leow
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
There is one side-effect of using this, though. Anonymous objects get created, which may not be fine always.
A large GUI application designed this way probably needs a bit more permgen space. Though I don't think it should take all that much space to store something which is essentially the classname and an initializer.
extraneon
Gotta say this is a better use of the static initializers than #1, but wow. Is it really that much of an advantage over naming your frame "f" and your buttons b? Readability, I'd say that even the "Short" names are better than this if not just for the "No Surprises" factor.
Bill K
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
I like it too:) It's like JavaFX but gratis
Vlagged
Yep - I quite like the 'abused' version, I think that's really very clear and readable, but perhaps that's just me.
barryred
Absolutely agree, the hierarchy of the code reflecting the hierarchy of the gui is a huge improvement over a sequence of method calls.
opsb
+60  A: 

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.

Paul Wicks
The important thing about this is when calling the method, you can write: foo("first","second","third")
Steve Armstrong
I love this feature! Syntactic sugar, no less, but very nice!
mcjabberz
Thank you for teaching me the word "arity"!
Amanda S
so the old hello world can be rewritten;public static void main(String... args) { System.out.println("Hello World!");}
Karussell
+10  A: 

Javadoc - when written properly (not always the case with some developers unfortunately), it gives you a clear, coherent description of what code is supposed to do, as opposed to what it actually does. It can then be turned into a nice browsable set of HTML documentation. If you use continuous integration etc it can be generated regularly so all developers can see the latest updates.

and the beauty with which it pops up in Eclipse when you hover over a method...
Nivas
+3  A: 

SwingWorker for easily managing user interface callbacks from background threads.

Dan Vinton
A: 

Instances of the same class can access private members of other instances:

class Thing {
  private int x;

  public int addThings(Thing t2) {
    return this.x + t2.x;  // Can access t2's private value!
  }
}
David
that is both surprising and scary at the same time...
Chii
Why is this surprising?
Michael Myers
It was only until very recently that I learned this, and someone had to point it out to me in a comment left on my blog.
moffdub
It's surprising if you have exposure to an OO language other than C++.
Pete Kirkham
It's awful. Don't do it. It's not because I'm human that another human has the right to look into my bowels ;-)
cadrian
But how would you do a proper hash/equals implementation if you cant access its innards?
Chii
it is exactly the same logic that allows a method to access a private instance variable... private classes are part of the implementation, thus there should be no restrictions on the access between inner classes and the parent, the parent and inner classes, and inner classes to other inner classes.
TofuBeer
A: 

If you hook onto groovy, you will have many more surprises than these :-)

Well, that is not the question...
Tim Büthe
+3  A: 

Apparently with some debug builds there is an option which dumps the native (JIT) assembly code from HotSpot: http://weblogs.java.net/blog/kohsuke/archive/2008/03/deep_dive_into.html

Unfortunately I wasn't able to find the build via the link in that post, if anyone can find a more precise URL, I'd love to play with it.

Joe
http://download.java.net/jdk6/binaries and then for whatever platform you use the last link (with debug in the name). I loooooove that feature!
Adrian
+21  A: 

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.

stili
I love TimeUnit, good catch.
Willi
+9  A: 

The strictfp keyword. (I never saw it used in a real application though :)

You can get the class for primitive types by using the following notation: int.class, float.class, etc. Very useful when doing reflection.

Final arrays can be used to "return" values from anonymous inner classes (warning, useless example below):

final boolean[] result = new boolean[1];
SwingUtilities.invokeLater(new Runnable() {
  public void run() { result[0] = true; }
});
Romain Guy
using a final array to return from an anon inner class like that is probably not recommended good programming practice...
Chii
Romain Guy? Like, _the_ Romain Guy? ...Anyway, +1 for int.class. I thought Integer.TYPE was the only way.
Michael Myers
More than useless. The code immediately following this is likely to be executed before the EDT callback. Therefore it wont see the true value.
Tom Hawtin - tackline
I've used strictfp myself. This was for a program where potential movement of _double_ s between the registers (80-bits) and RAM (64-bits) could cause problems
Chinmay Kanchi
+49  A: 

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 )
{
    ...
}
Nice! Very nice!
mcjabberz
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.
Peter Dolberg
A: 

I enjoyed

  1. javadoc's taglet and doclet that enable us to customize javadoc output.
  2. JDK tools: jstat, jstack etc.
grayger
+3  A: 

The next-generation Java plugin found in Java 1.6 Update 10 and later has some very neat features:

  • Pass java_arguments parameter to pass arguments to the JVM that is created. This allows you to control the amount of memory given to the applet.
  • Create separate class loaders or even separate JVM's for each applet.
  • Specify the JVM version to use.
  • Install partial Java kernels in cases where you only need a subset of the full Java libraries' functionality.
  • Better Vista support.
  • Support (experimental) to drag an applet out of the browser and have it keep running when you navigate away.

Many other things that are documented here: http://jdk6.dev.java.net/plugin2/

More from this release here: http://jdk6.dev.java.net/6u10ea.html

sjbotha
+5  A: 

You can build a string sprintf-style using String.format().

String w = "world";
String s = String.format("Hello %s %d", w, 3);

You can of course also use special specifiers to modify the output.

More here: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax

sjbotha
How is that hidden?
OscarRyz
+11  A: 

with static imports you can do cool stuff like:

List<String> myList = list("foo", "bar");
Set<String> mySet = set("foo", "bar");
Map<String, String> myMap = map(v("foo", "2"), v("bar", "3"));
you could even do this with generics. Google Collections has nice utils for that.
Tim Büthe
+3  A: 

I like the static import of methods.

For example create the following util class:

package package.name;

public class util {

     private static void doStuff1(){
        //the end
     }

     private static String doStuff2(){
        return "the end";
     }

}

Then use it like this.

import static package.name.util.*;


public class main{

     public static void main(String[] args){
          dostuff1();// wee no more typing util.dostuff1()
          System.out.print(dostuff2()); // or util.dostuff2()
     }

}

Static Imports works with any class, Even Math...

import static java.lang.Math.*;
import static java.lang.System.out;
public class HelloWorld {
    public static void main(String[] args) {
        out.println("Hello World!");
        out.println("Considering a circle with a diameter of 5 cm, it has:");
        out.println("A circumference of " + (PI * 5) + "cm");
        out.println("And an area of " + (PI * pow(5,2)) + "sq. cm");
    }
}
youri
+10  A: 

List.subList returns a view on the original list

A documented but little known feature of lists. This allows you to work with parts of a list with changes mirrored in the original list.

List subList(int fromIndex, int toIndex)

"This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:

       list.subList(from, to).clear();

Similar idioms may be constructed for indexOf and lastIndexOf, and all of the algorithms in the Collections class can be applied to a subList."

chillitom
+15  A: 

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

netzwerg
As opposed to Callable<?>?
Chris Kaminski
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>.
netzwerg
Void is more specific than Object as Void can only be null, Object can be anything.
Peter Lawrey
+40  A: 

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; }
}
Peter Lawrey
neat! (gotta make this shit 15 characters though.)
Beau Martínez
This is madness. (+1)
Arian
+3  A: 

Intersection types allow you to (kinda sorta) do enums that have an inheritance hierarchy. You can't inherit implementation, but you can delegate it to a helper class.

enum Foo1 implements Bar {}
enum Foo2 implements Bar {}

class HelperClass {
   static <T extends Enum<T> & Bar> void fooBar(T the enum) {}
}

This is useful when you have a number of different enums that implement some sort of pattern. For instance, a number of pairs of enums that have a parent-child relationship.

enum PrimaryColor {Red, Green, Blue;}
enum PastelColor {Pink, HotPink, Rockmelon, SkyBlue, BabyBlue;}

enum TransportMedium {Land, Sea, Air;}
enum Vehicle {Car, Truck, BigBoat, LittleBoat, JetFighter, HotAirBaloon;}

You can write generic methods that say "Ok, given an enum value thats a parent of some other enum values, what percentage of all the possible child enums of the child type have this particular parent value as their parent?", and have it all typesafe and done without casting. (eg: that "Sea" is 33% of all possible vehicles, and "Green" 20% of all possible Pastels).

The code look like this. It's pretty nasty, but there are ways to make it better. Note in particuar that the "leaf" classes themselves are quite neat - the generic classes have declarations that are horribly ugly, but you only write them onece. Once the generic classes are there, then using them is easy.

import java.util.EnumSet;

import javax.swing.JComponent;

public class zz extends JComponent {

    public static void main(String[] args) {
     System.out.println(PrimaryColor.Green + " " + ParentUtil.pctOf(PrimaryColor.Green) + "%");
     System.out.println(TransportMedium.Air + " " + ParentUtil.pctOf(TransportMedium.Air) + "%");
    }


}

class ParentUtil {
    private ParentUtil(){}
    static <P extends Enum<P> & Parent<P, C>, C extends Enum<C> & Child<P, C>> //
    float pctOf(P parent) {
     return (float) parent.getChildren().size() / //
       (float) EnumSet.allOf(parent.getChildClass()).size() //
       * 100f;
    }
    public static <P extends Enum<P> & Parent<P, C>, C extends Enum<C> & Child<P, C>> //
    EnumSet<C> loadChildrenOf(P p) {
     EnumSet<C> cc = EnumSet.noneOf(p.getChildClass());
     for(C c: EnumSet.allOf(p.getChildClass())) {
      if(c.getParent() == p) {
       cc.add(c);
      }
     }
     return cc;
    }
}

interface Parent<P extends Enum<P> & Parent<P, C>, C extends Enum<C> & Child<P, C>> {
    Class<C> getChildClass();

    EnumSet<C> getChildren();
}

interface Child<P extends Enum<P> & Parent<P, C>, C extends Enum<C> & Child<P, C>> {
    Class<P> getParentClass();

    P getParent();
}

enum PrimaryColor implements Parent<PrimaryColor, PastelColor> {
    Red, Green, Blue;

    private EnumSet<PastelColor> children;

    public Class<PastelColor> getChildClass() {
     return PastelColor.class;
    }

    public EnumSet<PastelColor> getChildren() {
     if(children == null) children=ParentUtil.loadChildrenOf(this);
     return children;
    }
}

enum PastelColor implements Child<PrimaryColor, PastelColor> {
    Pink(PrimaryColor.Red), HotPink(PrimaryColor.Red), //
    Rockmelon(PrimaryColor.Green), //
    SkyBlue(PrimaryColor.Blue), BabyBlue(PrimaryColor.Blue);

    final PrimaryColor parent;

    private PastelColor(PrimaryColor parent) {
     this.parent = parent;
    }

    public Class<PrimaryColor> getParentClass() {
     return PrimaryColor.class;
    }

    public PrimaryColor getParent() {
     return parent;
    }
}

enum TransportMedium implements Parent<TransportMedium, Vehicle> {
    Land, Sea, Air;

    private EnumSet<Vehicle> children;

    public Class<Vehicle> getChildClass() {
     return Vehicle.class;
    }

    public EnumSet<Vehicle> getChildren() {
     if(children == null) children=ParentUtil.loadChildrenOf(this);
     return children;
    }
}

enum Vehicle implements Child<TransportMedium, Vehicle> {
    Car(TransportMedium.Land), Truck(TransportMedium.Land), //
    BigBoat(TransportMedium.Sea), LittleBoat(TransportMedium.Sea), //
    JetFighter(TransportMedium.Air), HotAirBaloon(TransportMedium.Air);

    private final TransportMedium parent;

    private Vehicle(TransportMedium parent) {
     this.parent = parent;
    }

    public Class<TransportMedium> getParentClass() {
     return TransportMedium.class;
    }

    public TransportMedium getParent() {
     return parent;
    }
}
paulmurray
A: 

Casting/Conversion by precedence in Java 1.4, this code:

int a = 2;
System.out.println(new Integer(a++).toString());

Can be "represented" like this:

int a = 2;
System.out.println(""+(a++));
ramayac
+5  A: 

Read "Java Puzzlers" by Joshua Bloch and you will be both enlightened and horrified.

David Plumpton
+5  A: 

Source code URLs. E.g. here is some legal java source code:

http://google.com

(Yes, it was in Java Puzzlers. I laughed...)

David Plumpton
...it's silly if you have a syntax highlighter.
Vuntic
+5  A: 

People are sometimes a bit surprised when they realize that it's possible to call private methods and access/change private fields using reflection...

Consider the following class:

public class Foo {
    private int bar;

    public Foo() {
        setBar(17);
    }

    private void setBar(int bar) {
        this.bar=bar;
    }

    public int getBar() {
        return bar;
    }

    public String toString() {
        return "Foo[bar="+bar+"]";
    }
}

Executing this program...

import java.lang.reflect.*;

public class AccessibleExample {
    public static void main(String[] args)
        throws NoSuchMethodException,IllegalAccessException, InvocationTargetException, NoSuchFieldException {
        Foo foo=new Foo();
        System.out.println(foo);

        Method method=Foo.class.getDeclaredMethod("setBar", int.class);
        method.setAccessible(true);
        method.invoke(foo, 42);

        System.out.println(foo);
        Field field=Foo.class.getDeclaredField("bar");
        field.setAccessible(true);
        field.set(foo, 23);
        System.out.println(foo);
    }
}

...will yield the following output:

Foo[bar=17]
Foo[bar=42]
Foo[bar=23]
Huxi
+7  A: 

Part feature, part bother: Java's String handling to make it 'appear' a native Type (use of operators on them, +, +=)

Being able to write:

String s = "A";
s += " String"; // so s == "A String"

is very convenient, but is simply syntactic sugar for (ie gets compiled to):

String s = new String("A");
s = new StringBuffer(s).append(" String").toString();

ergo an Object instantiation and 2 method invocations for a simple concatenation. Imagine Building a long String inside a loop in this manner!? AND all of StringBuffer's methods are declared synchronized. Thankfully in (I think) Java 5 they introduced StringBuilder which is identical to StringBuffer without the syncronization.

A loop such as:

String s = "";
for (int i = 0 ; i < 1000 ; ++i)
  s += " " + i; // Really an Object instantiation & 3 method invocations!

can (should) be rewritten in your code as:

StringBuilder buf = new StringBuilder(); // Empty buffer
for (int i = 0 ; i < 1000 ; ++i)
  buf.append(' ').append(i); // Cut out the object instantiation & reduce to 2 method invocations
String s = buf.toString();

and will run approximately 80+% faster than the original loop! (up to 180% on some benchmarks I have run)

AaronG
The literal `"A"` really is a java.lang.String, though its backing character array is allocated in a different way to dynamically-created strings.
Donal Fellows
+7  A: 

Perhaps the most surprising hidden feature is the sun.misc.Unsafe class.

http://www.docjar.com/html/api/ClassLib/Common/sun/misc/Unsafe.java.html

You can;

  • Create an object without calling a constructor.
  • Throw any exception even Exception without worrying about throws clauses on methods. (There are other way to do this I know)
  • Get/set randomly accessed fields in an object without using reflection.
  • allocate/free/copy/resize a block of memory which can be long (64-bit) in size.
  • Obtain the location of fields in an object or static fields in a class.
  • independently lock and unlock an object lock. (like synchronize without a block)
  • define a class from provided byte codes. Rather than the classloader determining what the byte code should be. (You can do this with reflection as well)

BTW: Incorrect use of this class will kill the JVM. I don't know which JVMs support this class so its not portable.

Peter Lawrey
That's not a hidden feature of Java but a hidden feature of some specific JVM implementations.
Nat
True, though I haven't come across a JSE which doesn't have it.If any one knows one I would be interested.
Peter Lawrey
+22  A: 

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");
Ron
/me wonders why this is useful at all
Vuntic
@Vuntic - It does allow you to define a simple class within the context that it is needed.
ChaosPandion
+5  A: 

An optimization trick that makes your code easier to maintain and less susceptible to a concurrency bug.

public class Slow {
  /** Loop counter; initialized to 0. */
  private long i;

  public static void main( String args[] ) {
    Slow slow = new Slow();

    slow.run();
  }

  private void run() {
    while( i++ < 10000000000L )
      ;
  }
}

$ time java Slow
real 0m15.397s
$ time java Slow
real 0m20.012s
$ time java Slow
real 0m18.645s

Average: 18.018s

public class Fast {
  /** Loop counter; initialized to 0. */
  private long i;

  public static void main( String args[] ) {
    Fast fast = new Fast();

    fast.run();
  }

  private void run() {
    long i = getI();

    while( i++ < 10000000000L )
      ;

    setI( i );
  }

  private long setI( long i ) {
    this.i = i;
  }

  private long getI() {
    return this.i;
  }
}

$ time java Fast
real 0m12.003s
$ time java Fast
real 0m9.840s
$ time java Fast
real 0m9.686s

Average: 10.509s

It requires more bytecodes to reference a class-scope variable than a method-scope variable. The addition of a method call prior to the critical loop adds little overhead (and the call might be inlined by the compiler anyway).

Another advantage to this technique (always using accessors) is that it eliminates a potential bug in the Slow class. If a second thread were to continually reset the value of i to 0 (by calling slow.setI( 0 ), for example), the Slow class could never end its loop. Calling the accessor and using a local variable eliminates that possibility.

Tested using J2SE 1.6.0_13 on Linux 2.6.27-14.

Dave Jarvis
but Fast is not the same as Slow: the value of member "Fast.i" is NOT changed by/after the loop. If you call the run() method a second time, Slow will be much faster (increments "i" only once) and Fast will be as slows before since "Fast.i" is still zero.
Carlos Heuberger
You are correct, Carlos. To make Fast and Slow have the same behaviour (in a single-threaded environment), the instance variable "i" would have to be updated at the end of the "run" method, which would not significantly impact performance.
Dave Jarvis
also got a "strange" result using System.currentTimeMillis() around the call to calculate the runtime: slow is faster than fast (slow=40.6s, fast=42.9s) for 1.6.0_13-b03 on WindowsXP
Carlos Heuberger
Carlos: Try four runs for both classes without any potentially CPU-intensive programs running (e.g., virus checker, system update, browser). Also, throw out the first run in both test volleys. That Fast is slower than Slow by ~2 seconds leads me to believe something interfered with the runs. (That is, it should not take 2 seconds to get and set a variable via its accessor.)
Dave Jarvis
"Premature optimization" is a phrase used to describe a situation where a programmer lets performance considerations affect the design of a piece of code. This can result in a design that is not as clean as it could have been or code that is incorrect, because the code is complicated by the optimization and the programmer is distracted by optimizing. [ref: http://en.wikipedia.org/wiki/Optimization_%28computer_science%29]
jdigital
@jdigital: I do not consider it premature. When methods are synchronized, it protects against the following problem: http://stackoverflow.com/questions/2458217/why-does-this-code-sometimes-throw-a-nullpointerexception
Dave Jarvis
A: 

Java Bean property accessor methods do not have to start with "get" and "set".

Even Josh Bloch gets this wrong in Effective Java.

Nat
Well, of course they don't it's more of a code convention. Many frameworks/apis rely on reflection to access your properties, so not using get(is)/set is just asking for troubles.
serg
That's proving my point. The use of get/set prefixes is taken from the Java Beans API and is just the default naming convention, not mandatory. But authors of poorly designed frameworks/APIs seem not to know this. They hard-code a naming convention that classes must use to work with their framework (and then have the cheek to say that their framework supports POJOs; mandating a naming convention, by definition, makes their framework not support POJOs).
Nat
+5  A: 

I just (re)learned today that $ is a legal name for a method or variable in Java. Combined with static imports it can make for some slightly more readable code, depending on your view of readable:

http://garbagecollected.org/2008/04/06/dollarmaps/

Peter Recore
The $ symbol is also used for distinguishing inner classes from their enclosing classes in most compilers.
Dave Jarvis
You can also use £ and € signs in variable names. As well as any UNICODE letters æ, ø, å etc.
Superfilin
+4  A: 

It has already been mentioned that a final array can be used to pass a variable out of the anonymous inner classes.

Another, arguably better and less ugly approach though is to use AtomicReference (or AtomicBoolean/AtomicInteger/…) class from java.util.concurrent.atomic package.

One of the benefits in doing so is that these classes also provide such methods as compareAndSet, which may be useful if you're creating several threads which can modify the same variable.


Another useful related pattern:

final AtomicBoolean dataMsgReceived = new AtomicBoolean(false);
final AtomicReference<Message> message = new AtomicReference<Message>();
withMessageHandler(new MessageHandler() {
    public void handleMessage(Message msg) {
         if (msg.isData()) {
             synchronized (dataMsgReceived) {
                 message.set(msg);
                 dataMsgReceived.set(true);
                 dataMsgReceived.notifyAll();
             }
         }
    }
}, new Interruptible() {
    public void run() throws InterruptedException {
        synchronized (dataMsgReceived) {
            while (!dataMsgReceived.get()) {
                dataMsgReceived.wait();
            }
        }
    }
});

In this particular example we could have simply waited on message for it to become non-null, however null may often be a valid value and then you need to use a separate flag to finish the wait.

waitMessageHandler(…) above is yet another useful pattern: it sets up a handler somewhere, then starts executing the Interruptible which may throw an exception, and then removes the handler in the finally block, like so:

private final AtomicReference<MessageHandler> messageHandler = new AtomicReference<MessageHandler>();
void withMessageHandler(MessageHandler handler, Interruptible logic) throws InterruptedException {
    synchronized (messageHandler) {
        try {
            messageHandler.set(handler);
            logic.run();
        } finally {
            messageHandler.set(null);
        }
    }
}

Here I assume that the messageHandler's (if it's not null) handleMessage(…) method is called by another thread when a message is received. messageHandler must not be simply of MessageHandler type: that way you will synchronize on a changing variable, which is clearly a bug.

Of course, it doesn't need to be InterruptedException, it could be something like IOException, or whatever makes sense in a particular piece of code.

ivant
+4  A: 

Comma & array. It is legal syntax: String s[] = {
"123" ,
"234" ,
};

sibnick
+6  A: 

Most people does not know they can clone an array.

int[] arr = {1, 2, 3};
int[] arr2 = arr.clone();
mdakin
You can call `clone` on any `Object`. You just need to be careful that the `Object` implements a deep clone.
Finbarr
@Finbarr: Quite the reverse. It does a shallow clone; the inner objects just get another reference to them. The “simplest” way to deep clone is to serialize and deserialize, or to actually understand what you're making a copy of.
Donal Fellows
+3  A: 

Use StringWriter instead of StringBuffer when you don't need synchronized management included in StringBuffer. It will increase the performance of your application.

Improvements for Java 7 would be even better than any hidden Java features:

  • Diamond syntax: Link

Don't use those infinite <> syntax at instanciation:

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();

// Can now be replaced with this:

Map<String, List<String>> anagrams = new HashMap<>();
  • Strings in switch: Link

Use String in switch, instead of old-C int:

String s = "something";
switch(s) {
 case "quux":
    processQuux(s);
    // fall-through

  case "foo":
  case "bar":
    processFooOrBar(s);
    break;

  case "baz":
     processBaz(s);
    // fall-through

  default:
    processDefault(s);
    break;
}
  • Automatic Resource Management Link

This old code:

static void copy(String src, String dest) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dest);
        try {
            byte[] buf = new byte[8 * 1024];
            int n;
            while ((n = in.read(buf)) >= 0)
                out.write(buf, 0, n);
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}

can now be replaced by this much simpler code:

static void copy(String src, String dest) throws IOException {
        try (InputStream in = new FileInputStream(src);
             OutputStream out = new FileOutputStream(dest)) {
            byte[] buf = new byte[8192];
            int n;
            while ((n = in.read(buf)) >= 0)
                out.write(buf, 0, n);
        }
    }
}
Lastnico
Do you mean `StringBuilder` instead of `StringWriter`? The APIs for `StringBuffer` and `StringBuilder` are the same however using `StringWriter` would require some code changes.
pjp
Is the automatic resource management actually available?
Casebash
+2  A: 

You can switch(this) inside method definitions of enum classes. Made me shout "whut!" loudly when I discovered that this actually works.

Wow, `switch` works with `enum`’s… big surprise.
Bombe
+3  A: 

Actually, what I love about Java is how few hidden tricks there are. It's a very obvious language. So much so that after 15 years, almost every one I can think of is already listed on these few pages.

Perhaps most people know that Collections.synchronizedList() adds synchronization to a list. What you can't know unless you read the documentation is that you can safely iterate on the elements of that list by synchronizing on the list object itself.

CopyOnWriteArrayList might be unknown to some, and Future represents an interesting way to abstract multithreaded result access.

You can attach to VMs (local or remote), get information on GC activity, memory use, file descriptors and even object sizes through the various management, agent and attach APIs.

Although TimeUnit is perhaps better than long, I prefer Wicket's Duration class.

Jonathan Locke
+7  A: 

Oh, I almost forgot this little gem. Try this on any running java process:

jmap -histo:live PID

You will get a histogram of live heap objects in the given VM. Invaluable as a quick way to figure certain kinds of memory leaks. Another technique I use to prevent them is to create and use size-bounded subclasses of all the collections classes. This causes quick failures in out-of-control collections that are easy to identify.

Jonathan Locke
+6  A: 

A feature with which you can display splash screens for your Java Console Based Applications.

Use the command line tool "java" or "javaw" with the option -splash

eg: java -splash:C:\myfolder\myimage.png -classpath myjarfile.jar com.my.package.MyClass

the content of C:\myfolder\myimage.png will be displayed at the center of your screen, whenever you execute the class "com.my.package.MyClass"

Ashish
That's really kind of hidden... can't find the option in the documentation for the java (java.exe) command. (but it's on the help message or javadoc of SplashScreen)
Carlos Heuberger
+14  A: 

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

Devon_C_Miller
Didn't work for me :( ubuntu/java6
aioobe
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
Devon_C_Miller
A: 

Surprises me that an interface can extend multiple interfaces but class can extend only one class.

fastcodejava
Not really. There's never any issues as to "which superclass implementation should be called", since there are no implementations.
Hugo
+38  A: 

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

crowne
This just made my day better. Thanks!
Dean J
This deserves to be higher up in that thread.
Willi
+7  A: 

Shutdown Hooks. This allows to register a thread that will be created immediatly but started only when the JVM ends ! So it is some kind of "global jvm finalizer", and you can make usefull stuff in this thread (for example shutting down java ressources like an embedded hsqldb server). This works with System.exit(), or with CTRL-C / kill -15 (but not with kill -9 on unix, of course).

Moreover it's pretty easy to set up.

            Runtime.getRuntime().addShutdownHook(new Thread() {
                  public void run() {
                      endApp();
                  }
            });;
Sergio
They're great! You can unregister them too (if you keep around a reference) so you can do nice cleanup of resources. I use them – in conjunction with Spring lifecycle callbacks, especially the `destroy-method` attribute – for killing off worker subprocesses.
Donal Fellows
+5  A: 

Identifiers can contain foreign language chars like umlauts:

instead of writing:

String title="";

someone could write:

String Überschrift="";
stacker
and you can access it like `\u00dcberschrift = "OK";`
Carlos Heuberger
Not good style in my opinion. You know what I mean if you ever had to work with some code with comments and identifiers in a language you do not understand. Code should not be localized.
deepc
@deepc - "`Hidden` Features" may be no good style IMO...
Carlos Heuberger
A: 

Java 6 (from Sun) comes with an embedded JavaScrip interpreter.

http://java.sun.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html#jsengine

nos
+3  A: 

Didn't read about this

Integer integ1_a = 1;
Integer integ1_b = 1;
Integer integ1_c = new Integer(1);
Integer integ1_d = new Integer(1);

Integer integ128_a = 128;
Integer integ128_b = 128;

assertTrue (integ1_a   == integ1_b);   // again: this is true!
assertFalse(integ128_a == integ128_b); // again: this is false!
assertFalse(integ1_c   == integ1_d);   // again: this is false!

read more about this by searching java's pool of integer (internal 'cache' from -128 to 127 for autoboxing) or look into Integer.valueOf

Karussell
A: 

You can override a method and have the superclass constructor call it (this may come as a surprise to C++ programmers.)

Example

finnw
+12  A: 

Here's my list.

My favourite (and scariest) hidden feature is that you can throw checked exceptions from methods that are not declaring to throw anything.

import java.rmi.RemoteException;

class Thrower {
    public static void spit(final Throwable exception) {
        class EvilThrower<T extends Throwable> {
            @SuppressWarnings("unchecked")
            private void sneakyThrow(Throwable exception) throws T {
                throw (T) exception;
            }
        }
        new EvilThrower<RuntimeException>().sneakyThrow(exception);
    }
}

public class ThrowerSample {
    public static void main( String[] args ) {
        Thrower.spit(new RemoteException("go unchecked!"));
    }
}

Also you may like to know you can throw 'null'...

public static void main(String[] args) {
     throw null;
}

Guess what this prints:

Long value = new Long(0);
System.out.println(value.equals(0));

And, guess what this returns:

public int returnSomething() {
    try {
        throw new RuntimeException("foo!");
    } finally {
        return 0;
    }
}

the above should not surprise good developers.


In Java you can declare an array in following valid ways:

String[] strings = new String[] { "foo", "bar" };
// the above is equivalent to the following:
String[] strings = { "foo", "bar" };

So following Java code is perfectly valid:

public class Foo {
    public void doSomething(String[] arg) {}

    public void example() {
        String[] strings = { "foo", "bar" };
        doSomething(strings);
    }
}

Is there any valid reason why, instead, the following code shouldn't be valid?

public class Foo {

    public void doSomething(String[] arg) {}

    public void example() {
        doSomething({ "foo", "bar" });
    }
}

I think, that the above syntax would have been a valid substitute to the varargs introduced in Java 5. And, more coherent with the previously allowed array declarations.

Luigi R. Viggiano
The valid reason is that the compiler can't infer the type of the array. But good list.
CurtainDog
Isnt the doSomething({"",""}) something that will be supported with simple closures in Java 7?
Shervin
+9  A: 

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

(Explanation)

Dolph
+1  A: 

You can add runtime checks of generic types using a Class<T> object, this comes in handy when a class is being created in a configuration file somewhere and there is no way to add a compile time check for the generic type of the class. You dont want the class to blow up at runtime if the app happens to be configured wrong and you dont want all you classes riddled with instance of checks.

public interface SomeInterface {
  void doSomething(Object o);
}
public abstract class RuntimeCheckingTemplate<T> {
  private Class<T> clazz;
  protected RuntimeChecking(Class<T> clazz) {
    this.clazz = clazz;
  }

  public void doSomething(Object o) {
    if (clazz.isInstance(o)) {
      doSomethingWithGeneric(clazz.cast(o));
    } else {
      // log it, do something by default, throw an exception, etc.
    }
  }

  protected abstract void doSomethingWithGeneric(T t);
}

public class ClassThatWorksWithStrings extends RuntimeCheckingTemplate<String> {
  public ClassThatWorksWithStrings() {
     super(String.class);
  }

  protected abstract void doSomethingWithGeneric(T t) {
    // Do something with the generic and know that a runtime exception won't occur 
    // because of a wrong type
  }
}
Yanamon
A: 

I was surprised when I first noticed the Ternary-Operator which equals a simple if-then-else statement:

minVal = (a < b) ? a : b;
234352
IMHO it's neither hidden nor suprising, most languages i know have it (C, C++, C#, PHP, Perl, Javascript, ...)
dbemerlin
I know that by now, but a few weeks ago I did not think of such an operator. It is probably because I am not too expierienced, but my mind was somewhat blown :D
234352
I agree with @dbermerlin. This is NOT a hidden feature. It very common.
Shervin
+3  A: 

I can add Scanner object. It is the best for parsing.

String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
mbenturk
In my opinion, this is not a hidden feature. The Scanner is a library.
Shervin
+5  A: 

You can define and invoke methods on anonymous inner classes.

Well they're not that hidden, but very few people know they can be used to define a new method in a class and invoke it like this:

(new Object() {
    public String someMethod(){ 
        return "some value";
    }
}).someMethod();

Probably is not very common because it not very useful either, you can call the method it only when you define it ( or via reflection )

OscarRyz
Looks a little bit like the JavaScript module pattern ;)
Johannes Wachter
+9  A: 

This is not really a hidden feature but it did give me a big superise when I saw this compiled fine:

public int aMethod(){
    http://www.google.com
    return 1;
}

the reason why it compiles is that the line http://www.google.com the "http:" part is treated by the compiler as a label and the rest of the line is a comment.

So, if you want to write some bizzare code (or obfuscated code), just put alot of http addresses there. ;-)

Jason Wang
Most likely useless, but cool nonetheless :)
Cambium
Cool :) You got this from java puzzlers right ;)?
Alfred
but more than a year old. See this answer from "David Plumpton" at May 12 '09: http://stackoverflow.com/questions/15496/hidden-features-of-java/851055#851055 (and he only got 2 upvotes...)
Carlos Heuberger
This is a duplicate answer
Shervin
+7  A: 

The C-Style printf() :)

System.out.printf("%d %f %.4f", 3,Math.E,Math.E);

Output: 3 2.718282 2.7183

Binary Search (and it's return value)

int[] q = new int[] { 1,3,4,5};
int position = Arrays.binarySearch(q, 2);

Similar to C#, if '2' is not found in the array, it returns a negative value but if you take the 1's Complement of the returned value you actually get the position where '2' can be inserted.

In the above example, position = -2, ~position = 1 which is the position where 2 should be inserted...it also lets you find the "closest" match in the array.

I thinks its pretty nifty... :)

st0le
`printf` is not hidden, neither is the working of `binarySearch`.
Carlos Heuberger
No feature mentioned in the previous answers are exactly "hidden". Most of them are just "relatively unknown" to the common java programmer. Atleast that's what i thought the question was...
st0le
the binarySearch a hack but a really good one :-)
Helper Method
+7  A: 

Not so hidden, but interesting.

You can have a "Hello, world" without main method ( it throws NoSuchMethodError thought )

Originally posted by RusselW on Strangest language feature

public class WithoutMain {
    static {
        System.out.println("Look ma, no main!!");
        System.exit(0);
    }
}

$ java WithoutMain
Look ma, no main!!
OscarRyz
Add a `System.exit(0);` to suppress that ugly exception…
Donal Fellows