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.
33 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 '08 at 12:02 4 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 '08 at 8:48 45 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 '08 at 13:05 43 "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 '08 at 14:27 8 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 Mar 11 '09 at 9:49.
Joint union in type parameter variance: public class Baz {} For example, if you wanted to take a parameter that's both Comparable and a Collection: public static & Comparable> 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.
– dubdubdubdot Jun 16 '09 at 18:37 8 @Grasper: No, OR (disjoint union) is not provided in that context. But you can use a disjoint union datatype like Either instead. This type is the dual of a Pair type.
Look at the Functional Java library or the Scala core libraries for an example of such a datatype. – Apocalisp Jun 16 '09 at 21:51 1 You should said that you MUST extends only one class and several interfaces -> public class Baz – JohnJohnGa Oct 17 at 8:53.
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 numbers = new ArrayList(){{ add(1); add(2); }}; Map codes = new HashMap(){{ put("1","one"); put("2","two"); }}.
34 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 安宇 Oct 10 '08 at 15:45 30 Also, unlike an init() method, it can initialize final fields.
– Darron Jan 7 '09 at 18:45 2 What if you extend the class and instantiate various children? Will it still behave in the same manner? – Kezzer Jan 27 '09 at 12:48 10 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 '09 at 8:46 10 I bet even "java in 24 hours" book has this "obvious feature". Read more guys :)( – Comptrol May 6 '09 at 19:40.
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.
7 Dude! That rocks! – Ogre Psalm33 Oct 9 '08 at 16:45 6 more info on VisualVM: visualvm.dev.java.Net – ManBugra Apr 16 '10 at 21:01 2 +1: This ought to be more widely known.
– Donal Fellows May 26 '10 at 13:13.
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.
35 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 Sep 19 '08 at 13:35 21 ...considered harmful. – Andreas Petersson Sep 30 '08 at 7:43 27 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 '08 at 18:57 64 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 Apr 20 '09 at 4:10 25 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 '09 at 13:38.
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 values() { ... } } class ThreadSafeSortedSub extends Souper { @Override ConcurrentSkipListSet 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.
20 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 Sep 14 '08 at 15:04.
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 jamesjava.blogspot.com/2006/03/dont-retu....
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... – Neil Coffey Apr 20 '09 at 3:54 14 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 '09 at 20:00.
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.
5 This just made my day better. Thanks! – Dean J Aug 4 '10 at 20:29.
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.
16 Really awesome feature actually--makes enums OO and solves a lot of initialization problems in a very clean way. – Bill K Oct 6 '08 at 18:00 4 Enum as singleton? Enum with only one value?
– Georgy Bolyuba Nov 13 '08 at 0:01 3 Georgy: Singleton is one instance of the object, not an object with one value. – dshaw Nov 17 '08 at 22:43 18 @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 '09 at 8:57.
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 ) { ... }.
6 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 Dec 24 '09 at 16:20.
The type params for generic methods can be specified explicitly like so: Collections.emptyMap().
8 And by god is it ugly and confusing. And irrelevant to type safety. – broady Sep 16 '08 at 12:21 8 I love URL1 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 '09 at 15:30 6 This is actually very useful in situations where you have declared a static generic method such as public static T foo(T t). You can then make calls to Class. Foo(t); – Finbarr May 13 '10 at 8:20.
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.
22 The important thing about this is when calling the method, you can write: foo("first","second","third") – Steve Armstrong Mar 25 '09 at 20:03 32 Thank you for teaching me the word "arity"! – Amanda S Oct 14 '09 at 17:28 9 so the old hello world can be rewritten; public static void main(String... args) { System.out. Println(""); } – Karussell Jan 22 '10 at 21:56.
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; } }.
7 neat! (gotta make this shit 15 characters though. ) – Beau Martínez Jun 10 '09 at 0:37 16 This is madness.(+1) – Arian Oct 4 '10 at 11:33 2 @Arian this isn't madness.THIS.IS.
JAVAAAAAAHHHH! – Santiago Lezica Oct 13 at 12:45.
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(" 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(" there"){{ setBackground(Color. Black); setForeground( Color.
White); }}); add( new JButton("Ok"){{ addActionListener( new ActionListener(){ public void actionPerformed( ActionEvent ae ){ System.out. Println("Button pushed"); } }); }}); }}); }}.
13 There is one side-effect of using this, though. Anonymous objects get created, which may not be fine always. – amit Feb 10 '09 at 8:14 14 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 '09 at 21:32 3 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 '10 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 '10 at 9:08.
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.
7 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 '10 at 19:57.
My favorite: dump all thread stack traces to standard out. Windows: CTRL-Break in your java cmd/console window unix: kill -3 PID.
11 Also ctrl-\ in Unix. Or use jstack from the JDK. – Tom Hawtin - tackline Sep 17 '08 at 14:53 1 Or use jvisualvm.
– JesperE Aug 20 '09 at 11:55 7 Thanks, you just taught me my keyboard has a Break key. – Coronatus Aug 18 '10 at 22:53 1 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 Aug 24 '10 at 20:40.
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; }.
25 Yes, but more strongly: "The value of a final variable must be set once" – Allain Lalonde Feb 4 '09 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. – Neil Coffey Apr 20 '09 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 '09 at 21:31.
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.
16 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 '09 at 17:33 28 Java 7 will have new bytecodes to support dynamic languages. – Michael Borgwardt Aug 14 '09 at 9:40 13 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 '09 at 15:43 11 @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 Nov 27 '09 at 8:12 10 JVM doesn't support generics, while the .
NET VM does. JVM is nowhere near the best. – Blindy Nov 27 '09 at 8:52.
The asList method in java.util. Arrays allows a nice combination of varargs, generic methods and autoboxing: List ints = Arrays. AsList(1,2,3).
14 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 '09 at 13:39.
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(""); 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!
3 This one is in Java Puzzlers. – cdmckay Feb 23 '09 at 7:31 14 neat, a label with a comment :) – Thorbjørn Ravn Andersen May 26 '09 at 7:57.
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("").
– Thorbjørn Ravn Andersen Dec 3 '10 at 14:19 11 new Thread() { public void run() { ... } }.start(); – Wouter Lievens May 2 at 13:08 5 @Wouter - In that case, the method which is called on the anonymous object (start()) is not actually defined in the subclass... – Axel Aug 2 at 8:35.
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); } }; }.
18 that is a sun. * API which isn't really part of the Java language per se – DW. Mar 5 '09 at 2:53.
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() { public int compare(Integer o1, Integer o2) { if (sortAscending || ContainerClass.this. SortAscending) { return o1 - o2; } else { return o2 - o1; } } }; return comparator; } }.
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 '09 at 17:12 4 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 '09 at 19:13.
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 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 Jun 2 '10 at 14:40.
17 The trouble with assert is that it needs to be switched on during runtime. – extraneon May 21 '09 at 15:42 9 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 Aug 9 '09 at 5:15 5 I believe that’s a good thing about assert: it can be turned off without penalty. – andref Jul 11 '10 at 17:41.
The addition of the for-each loop construct in 1.5. I 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.
29 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 '09 at 7:28 21 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 '09 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 '09 at 15:32 3 @extraneon: take a look at Collections.
List(Enumeration e). That should help with iterating enumerations in the foreach loop. – deepc Mar 24 '10 at 23:49.
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.
Every class file starts with the hex value 0xCAFEBABE to identify it as valid JVM bytecode. (Explanation).
Not really part of the Java language, but the javap disassembler which comes with Sun's JDK is not widely known or used.
I personally discovered java.lang. Void very late -- improves code readability in conjunction with generics, e.g. Callable.
2 not quite. At some point, you need to be specific: Executors. NewSingleThreadExecutor().
Submit(new Callable() {..}) -- you can't instantiate a new Callable(), you need to specify an explicit type -- thus, it's an alternative to Callable. – netzwerg Jun 17 '09 at 14:59 1 Void is more specific than Object as Void can only be null, Object can be anything. – Peter Lawrey Jul 22 '10 at 21:14.
I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.