<p>After reading <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden Features of C#</a> I wondered, What are some of the hidden features of Java?</p>

[{'answer_id': 15512, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 5, 'selected': False, 'text': '<p>Language-level <strong>assert</strong> keyword.</p>\n'}, {'answer_id': 15533, 'author': 'Mo.', 'author_id': 1870, 'author_profile': 'https://Stackoverflow.com/users/1870', 'pm_score': 4, 'selected': False, 'text': '<p>I really like the rewritten Threading API from Java 1.6. Callables are great. They are basically threads with a return value.</p>\n'}, {'answer_id': 15538, 'author': 'Michael Neale', 'author_id': 699, 'author_profile': 'https://Stackoverflow.com/users/699', 'pm_score': 5, 'selected': False, 'text': '<p>static imports to "enhance" the language, so you can do nice literal things in type safe ways: </p>\n\n<pre><code>List&lt;String&gt; ls = List("a", "b", "c");\n</code></pre>\n\n<p>(can also do with maps, arrays, sets). </p>\n\n<p><a href="http://gleichmann.wordpress.com/2008/01/13/building-your-own-literals-in-java-lists-and-arrays/" rel="nofollow noreferrer">http://gleichmann.wordpress.com/2008/01/13/building-your-own-literals-in-java-lists-and-arrays/</a></p>\n\n<p>Taking it further: </p>\n\n<pre><code>List&lt;Map&lt;String, String&gt;&gt; data = List(Map( o("name", "michael"), o("sex", "male")));\n</code></pre>\n'}, {'answer_id': 16528, 'author': 'Mo.', 'author_id': 1870, 'author_profile': 'https://Stackoverflow.com/users/1870', 'pm_score': 6, 'selected': False, 'text': '<p>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.</p>\n\n<p>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.</p>\n\n<p>All those languages make use of the HotSpot optimizations. The VM is very well monitor and debuggable. </p>\n'}, {'answer_id': 16838, 'author': 'Boris Terzic', 'author_id': 1996, 'author_profile': 'https://Stackoverflow.com/users/1996', 'pm_score': 9, 'selected': False, 'text': '<p><a href="http://www.c2.com/cgi/wiki?DoubleBraceInitialization" rel="nofollow noreferrer">Double Brace Initialization</a> took me by surprise a few months ago when I first discovered it, never heard of it before.</p>\n\n<p><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/ThreadLocal.html" rel="nofollow noreferrer">ThreadLocals</a> are typically not so widely known as a way to store per-thread state.</p>\n\n<p>Since JDK 1.5 Java has had extremely well implemented and robust concurrency tools beyond just locks, they live in <a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html" rel="nofollow noreferrer">java.util.concurrent</a> and a specifically interesting example is the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/atomic/package-summary.html" rel="nofollow noreferrer">java.util.concurrent.atomic</a> subpackage that contains thread-safe primitives that implement the <a href="http://www.ibm.com/developerworks/java/library/j-jtp11234/" rel="nofollow noreferrer">compare-and-swap</a> operation and can map to actual native hardware-supported versions of these operations.</p>\n'}, {'answer_id': 17702, 'author': 'serg10', 'author_id': 1853, 'author_profile': 'https://Stackoverflow.com/users/1853', 'pm_score': 4, 'selected': False, 'text': '<p>Not really a feature, but it makes me chuckle that <strong><code>goto</code></strong> 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.</p>\n'}, {'answer_id': 17769, 'author': 'PPS', 'author_id': 2093, 'author_profile': 'https://Stackoverflow.com/users/2093', 'pm_score': 5, 'selected': False, 'text': '<p>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.</p>\n\n<p>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.</p>\n\n<p>JConsole in Java 5:\n<a href="http://java.sun.com/developer/technicalArticles/J2SE/jconsole.html" rel="nofollow noreferrer" title="Jconsole in Java 5">JConsole in Java 5</a></p>\n\n<p>JConsole in Java 6:\n<a href="http://java.sun.com/developer/technicalArticles/J2SE/monitoring/" rel="nofollow noreferrer" title="JConsole in Java 6">JConsole in Java 6</a></p>\n\n<p>And while you are at it, have a good look at the other tools in the series:\n<a href="http://java.sun.com/javase/6/docs/technotes/tools/index.html#troubleshoot" rel="nofollow noreferrer" title="Java 6 troubleshooting tools">Java 6 troubleshooting tools</a></p>\n'}, {'answer_id': 35084, 'author': 'John Meagher', 'author_id': 3535, 'author_profile': 'https://Stackoverflow.com/users/3535', 'pm_score': 4, 'selected': False, 'text': '<p>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.  </p>\n'}, {'answer_id': 35108, 'author': 'serg10', 'author_id': 1853, 'author_profile': 'https://Stackoverflow.com/users/1853', 'pm_score': 7, 'selected': False, 'text': "<p>How about <strong>covariant return types</strong> 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.  </p>\n\n<p>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:</p>\n\n<pre><code>class Souper {\n    Collection&lt;String&gt; values() {\n        ...\n    }\n}\n\nclass ThreadSafeSortedSub extends Souper {\n    @Override\n    ConcurrentSkipListSet&lt;String&gt; values() {\n        ...\n    }\n}\n</code></pre>\n\n<p>You can call the subclass's <code>values</code> method and obtain a sorted thread safe <code>Set</code> of <code>String</code>s <strong>without having to down cast</strong> to the <code>ConcurrentSkipListSet</code>.</p>\n"}, {'answer_id': 35124, 'author': 'Brad Barker', 'author_id': 12081, 'author_profile': 'https://Stackoverflow.com/users/12081', 'pm_score': 2, 'selected': False, 'text': '<p>Functors are pretty cool. They are pretty close to a function pointer, which everyone is usually quick to say is impossible in Java.</p>\n\n<p><a href="http://chaoticjava.com/posts/functors-in-java-and-beyond/" rel="nofollow noreferrer">Functors in Java</a></p>\n'}, {'answer_id': 39433, 'author': 'Georgy Bolyuba', 'author_id': 4052, 'author_profile': 'https://Stackoverflow.com/users/4052', 'pm_score': 7, 'selected': False, 'text': '<p>For most people I interview for Java developer positions labeled blocks are very surprising. Here is an example:</p>\n\n<pre><code>// code goes here\n\ngetmeout:{\n    for (int i = 0; i &lt; N; ++i) {\n        for (int j = i; j &lt; N; ++j) {\n            for (int k = j; k &lt; N; ++k) {\n                //do something here\n                break getmeout;\n            }\n        }\n    }\n}\n</code></pre>\n\n<p>Who said <code>goto</code> in java is just a keyword? :)</p>\n'}, {'answer_id': 40967, 'author': 'yalestar', 'author_id': 2177, 'author_profile': 'https://Stackoverflow.com/users/2177', 'pm_score': 4, 'selected': False, 'text': '<p>I was aware that Java 6 included scripting support, but I just recently discovered <a href="http://java.sun.com/javase/6/docs/technotes/tools/share/jrunscript.html" rel="nofollow noreferrer">jrunscript</a>, \nwhich 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</p>\n'}, {'answer_id': 41023, 'author': 'jodonnell', 'author_id': 4223, 'author_profile': 'https://Stackoverflow.com/users/4223', 'pm_score': 6, 'selected': False, 'text': '<p><a href="http://docs.oracle.com/javase/7/docs/technotes/guides/reflection/proxy.html" rel="nofollow noreferrer">Dynamic proxies</a> (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.</p>\n'}, {'answer_id': 42686, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 8, 'selected': False, 'text': "<p>Joint union in type parameter variance:</p>\n\n<pre><code>public class Baz&lt;T extends Foo &amp; Bar&gt; {}\n</code></pre>\n\n<p>For example, if you wanted to take a parameter that's both Comparable and a Collection:</p>\n\n<pre><code>public static &lt;A, B extends Collection&lt;A&gt; &amp; Comparable&lt;B&gt;&gt;\nboolean foo(B b1, B b2, A a) {\n   return (b1.compareTo(b2) == 0) || b1.contains(a) || b2.contains(a);\n}\n</code></pre>\n\n<p>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.</p>\n"}, {'answer_id': 44054, 'author': 'Matt Cummings', 'author_id': 828, 'author_profile': 'https://Stackoverflow.com/users/828', 'pm_score': 4, 'selected': False, 'text': '<p>I know this was added in release 1.5 but the new <em>enum type</em> is a great feature.  Not having to use the old "int enum pattern" has greatly helped a bunch of my code.  <a href="http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.9" rel="nofollow noreferrer">Check out JLS 8.9</a> for the sweet gravy on your potatoes!</p>\n'}, {'answer_id': 47347, 'author': 'dmeister', 'author_id': 4194, 'author_profile': 'https://Stackoverflow.com/users/4194', 'pm_score': 4, 'selected': False, 'text': "<p><strong>final for instance variables:</strong> </p>\n\n<p>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.</p>\n\n<hr>\n\n<p><strong>static {something;}:</strong> </p>\n\n<p>Used to initialize static members (also I prefer a static method to do it (because it has a name). Not thought.</p>\n"}, {'answer_id': 47493, 'author': 'David Carlson', 'author_id': 4901, 'author_profile': 'https://Stackoverflow.com/users/4901', 'pm_score': 8, 'selected': False, 'text': '<p>I was surprised by instance initializers the other day.  I was deleting some code-folded methods and ended up creating multiple instance initializers :</p>\n\n<pre><code>public class App {\n    public App(String name) { System.out.println(name + "\'s constructor called"); }\n\n    static { System.out.println("static initializer called"); }\n\n    { System.out.println("instance initializer called"); }\n\n    static { System.out.println("static initializer2 called"); }\n\n    { System.out.println("instance initializer2 called"); }\n\n    public static void main( String[] args ) {\n        new App("one");\n        new App("two");\n  }\n}\n</code></pre>\n\n<p>Executing the <code>main</code> method will display: </p>\n\n<pre><code>static initializer called\nstatic initializer2 called\ninstance initializer called\ninstance initializer2 called\none\'s constructor called\ninstance initializer called\ninstance initializer2 called\ntwo\'s constructor called\n</code></pre>\n\n<p>I guess these would be useful if you had multiple constructors and needed common code</p>\n\n<p>They also provide syntactic sugar for initializing your classes:</p>\n\n<pre><code>List&lt;Integer&gt; numbers = new ArrayList&lt;Integer&gt;(){{ add(1); add(2); }};\n\nMap&lt;String,String&gt; codes = new HashMap&lt;String,String&gt;(){{ \n  put("1","one"); \n  put("2","two");\n}};\n</code></pre>\n'}, {'answer_id': 49701, 'author': 'warsze', 'author_id': 4968, 'author_profile': 'https://Stackoverflow.com/users/4968', 'pm_score': 3, 'selected': False, 'text': '<p>Joshua Bloch\'s new <a href="https://rads.stackoverflow.com/amzn/click/com/0321356683" rel="noreferrer" rel="nofollow noreferrer">Effective Java</a> is a good resource.</p>\n'}, {'answer_id': 50107, 'author': 'Dan Dyer', 'author_id': 5171, 'author_profile': 'https://Stackoverflow.com/users/5171', 'pm_score': 3, 'selected': False, 'text': '<ul>\n<li><a href="http://www.unix.com.ua/orelly/java-ent/jnut/ch03_11.htm" rel="noreferrer">Local classes</a>.</li>\n<li><a href="http://virtualinfinity.net/wordpress/java/esoteric-java-features/2007/01/09/6/" rel="noreferrer">Instantiating Java inner-classes from outside of the containing class</a>.</li>\n</ul>\n'}, {'answer_id': 52914, 'author': 'Adrian Mouat', 'author_id': 4332, 'author_profile': 'https://Stackoverflow.com/users/4332', 'pm_score': 7, 'selected': False, 'text': '<p>Allowing methods and constructors in enums surprised me. For example:</p>\n\n<pre><code>enum Cats {\n  FELIX(2), SHEEBA(3), RUFUS(7);\n\n  private int mAge;\n  Cats(int age) {\n    mAge = age;\n  }\n  public int getAge() {\n    return mAge;\n   }\n}\n</code></pre>\n\n<p>You can even have a "constant specific class body" which allows a specific enum value to override methods.</p>\n\n<p>More documentation <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 54762, 'author': 'Binil Thomas', 'author_id': 3973, 'author_profile': 'https://Stackoverflow.com/users/3973', 'pm_score': 5, 'selected': False, 'text': "<p>Not really part of the Java language, but the javap disassembler which comes with Sun's JDK is not widely known or used.</p>\n"}, {'answer_id': 55221, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Self-bound generics:</p>\n\n<pre><code>class SelfBounded&lt;T extends SelfBounded&lt;T&gt;&gt; {\n}\n</code></pre>\n\n<p><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=136394" rel="nofollow noreferrer">http://www.artima.com/weblogs/viewpost.jsp?thread=136394</a></p>\n'}, {'answer_id': 55616, 'author': 'Kevin Wong', 'author_id': 4792, 'author_profile': 'https://Stackoverflow.com/users/4792', 'pm_score': 8, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 55679, 'author': 'Kevin Wong', 'author_id': 4792, 'author_profile': 'https://Stackoverflow.com/users/4792', 'pm_score': 7, 'selected': False, 'text': '<p>The type params for generic methods can be specified explicitly like so:</p>\n\n<pre><code>Collections.&lt;String,Integer&gt;emptyMap()\n</code></pre>\n'}, {'answer_id': 64136, 'author': 'Andrew', 'author_id': 7613, 'author_profile': 'https://Stackoverflow.com/users/7613', 'pm_score': 4, 'selected': False, 'text': '<p>It took them long enough to add support for this,</p>\n\n<p><a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/systemtray.html" rel="nofollow noreferrer">System Tray</a></p>\n'}, {'answer_id': 64164, 'author': 'Bruno De Fraine', 'author_id': 6918, 'author_profile': 'https://Stackoverflow.com/users/6918', 'pm_score': 6, 'selected': False, 'text': '<p>The <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html#asList(T...)" rel="nofollow noreferrer">asList</a> method in <code>java.util.Arrays</code> allows a nice combination of varargs, generic methods and autoboxing:</p>\n\n<pre><code>List&lt;Integer&gt; ints = Arrays.asList(1,2,3);\n</code></pre>\n'}, {'answer_id': 64274, 'author': 'Bruno De Fraine', 'author_id': 6918, 'author_profile': 'https://Stackoverflow.com/users/6918', 'pm_score': 3, 'selected': False, 'text': '<p>Some control-flow tricks, <code>finally</code> around a <code>return</code> statement:</p>\n\n<pre><code>int getCount() { \n  try { return 1; }\n  finally { System.out.println("Bye!"); }\n}\n</code></pre>\n\n<p>The rules for <a href="http://java.sun.com/docs/books/jls/third_edition/html/defAssign.html" rel="nofollow noreferrer">definite assignment</a> will check that a final variable is always assigned through a simple control-flow analysis:</p>\n\n<pre><code>final int foo;\nif(...)\n  foo = 1;\nelse\n  throw new Exception();\nfoo+1;\n</code></pre>\n'}, {'answer_id': 64369, 'author': 'Bill Michell', 'author_id': 7938, 'author_profile': 'https://Stackoverflow.com/users/7938', 'pm_score': 3, 'selected': False, 'text': "<p>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.</p>\n"}, {'answer_id': 64618, 'author': 'James A. N. Stauffer', 'author_id': 6770, 'author_profile': 'https://Stackoverflow.com/users/6770', 'pm_score': 7, 'selected': False, 'text': '<p>Transfer of control in a finally block throws away any exception.  The following code does not throw RuntimeException -- it is lost.</p>\n\n<pre><code>public static void doSomething() {\n    try {\n      //Normally you would have code that doesn\'t explicitly appear \n      //to throw exceptions so it would be harder to see the problem.\n      throw new RuntimeException();\n    } finally {\n      return;\n    }\n  }\n</code></pre>\n\n<p>From <a href="http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html" rel="nofollow noreferrer">http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html</a></p>\n'}, {'answer_id': 75519, 'author': '18Rabbit', 'author_id': 12662, 'author_profile': 'https://Stackoverflow.com/users/12662', 'pm_score': 5, 'selected': False, 'text': '<p>The addition of the for-each loop construct in 1.5.  I &lt;3 it.</p>\n\n<pre><code>// For each Object, instantiated as foo, in myCollection\nfor(Object foo: myCollection) {\n  System.out.println(foo.toString());\n}\n</code></pre>\n\n<p>And can be used in nested instances:</p>\n\n<pre><code>for (Suit suit : suits)\n  for (Rank rank : ranks)\n    sortedDeck.add(new Card(suit, rank));\n</code></pre>\n\n<p>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: </p>\n\n<pre><code>// Returns the sum of the elements of a\nint sum(int[] a) {\n  int result = 0;\n  for (int i : a)\n    result += i;\n  return result;\n}\n</code></pre>\n\n<p><a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html" rel="nofollow noreferrer">Link to the Sun documentation</a></p>\n'}, {'answer_id': 76317, 'author': 'Michael Myers', 'author_id': 13531, 'author_profile': 'https://Stackoverflow.com/users/13531', 'pm_score': 3, 'selected': False, 'text': '<p>"const" is a keyword, but you can\'t use it.</p>\n\n<pre><code>int const = 1;   // "not a statement"\nconst int i = 1; // "illegal start of expression"\n</code></pre>\n\n<p>I guess the compiler writers thought it might be used in the future and they\'d better keep it reserved.</p>\n'}, {'answer_id': 82236, 'author': 'PhiLho', 'author_id': 15459, 'author_profile': 'https://Stackoverflow.com/users/15459', 'pm_score': 6, 'selected': False, 'text': '<p>Not really a feature, but an amusing trick I discovered recently in some Web page:</p>\n\n<pre><code>class Example\n{\n  public static void main(String[] args)\n  {\n    System.out.println("Hello World!");\n    http://Phi.Lho.free.fr\n\n    System.exit(0);\n  }\n}\n</code></pre>\n\n<p>is a valid Java program (although it generates a warning).\nIf you don\'t see why, see Gregory\'s answer! ;-) Well, syntax highlighting here also gives a hint!</p>\n'}, {'answer_id': 83113, 'author': 'Chris Mazzola', 'author_id': 15816, 'author_profile': 'https://Stackoverflow.com/users/15816', 'pm_score': 7, 'selected': False, 'text': '<p>My favorite: dump all thread stack traces to standard out.</p>\n\n<p>windows: <kbd>CTRL</kbd>-<kbd>Break</kbd> in your java cmd/console window</p>\n\n<p>unix:  <code>kill -3 PID</code></p>\n'}, {'answer_id': 85703, 'author': 'mpresley', 'author_id': 12997, 'author_profile': 'https://Stackoverflow.com/users/12997', 'pm_score': 3, 'selected': False, 'text': '<p>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 <a href="http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html" rel="nofollow noreferrer">http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html</a>). </p>\n'}, {'answer_id': 101659, 'author': 'Tahir Akhtar', 'author_id': 18027, 'author_profile': 'https://Stackoverflow.com/users/18027', 'pm_score': 6, 'selected': False, 'text': '<p>Using <strong>this</strong> 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.</p>\n\n<pre><code>import java.util.Comparator;\n\npublic class ContainerClass {\nboolean sortAscending;\npublic Comparator createComparator(final boolean sortAscending){\n    Comparator comparator = new Comparator&lt;Integer&gt;() {\n\n        public int compare(Integer o1, Integer o2) {\n            if (sortAscending || ContainerClass.this.sortAscending) {\n                return o1 - o2;\n            } else {\n                return o2 - o1;\n            }\n        }\n\n    };\n    return comparator;\n}\n}\n</code></pre>\n'}, {'answer_id': 101851, 'author': 'Das', 'author_id': 17585, 'author_profile': 'https://Stackoverflow.com/users/17585', 'pm_score': 6, 'selected': False, 'text': '<p>This is not exactly "hidden features" and not very useful, but can be extremely interesting in some cases:<br>\nClass sun.misc.Unsafe - will allow you to implement <em>direct memory management</em> in Java (you can even write self-modifying Java code with this if you try a lot):</p>\n\n<pre><code>public class UnsafeUtil {\n\n    public static Unsafe unsafe;\n    private static long fieldOffset;\n    private static UnsafeUtil instance = new UnsafeUtil();\n\n    private Object obj;\n\n    static {\n        try {\n            Field f = Unsafe.class.getDeclaredField("theUnsafe");\n            f.setAccessible(true);\n\n            unsafe = (Unsafe)f.get(null);\n            fieldOffset = unsafe.objectFieldOffset(UnsafeUtil.class.getDeclaredField("obj"));\n        } catch (Exception e) {\n            throw new RuntimeException(e);\n        }\n    };\n}\n</code></pre>\n'}, {'answer_id': 107067, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Since no one else has said it yet (I Think) my favorite feature is Auto boxing!</p>\n\n<pre><code>public class Example\n{\n    public static void main(String[] Args)\n    {\n         int a = 5;\n         Integer b = a; // Box!\n         System.out.println("A : " + a);\n         System.out.println("B : " + b);\n    }\n}\n</code></pre>\n'}, {'answer_id': 129378, 'author': 'Alan Moore', 'author_id': 20938, 'author_profile': 'https://Stackoverflow.com/users/20938', 'pm_score': 3, 'selected': False, 'text': '<p>How about Properties files in your choice of encodings?  Used to be, when you loaded your Properties, you provided an InputStream and the <code>load()</code> method decoded it as ISO-8859-1.  You <em>could</em> 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: </p>\n\n<pre><code>String realProp = new String(prop.getBytes("ISO-8859-1"), "UTF-8");\n</code></pre>\n\n<p>But, as of JDK 1.6, there\'s a <code>load()</code> method that takes a Reader instead of an InputStream, which means you can use the correct encoding from the beginning (there\'s also a <code>store()</code> 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.</p>\n'}, {'answer_id': 137600, 'author': 'Kevin Day', 'author_id': 10973, 'author_profile': 'https://Stackoverflow.com/users/10973', 'pm_score': 5, 'selected': False, 'text': '<p>If you do a lot of JavaBean development and work with property change support, you generally wind up writing a <em>lot</em> of setters like this:</p>\n\n<pre><code>public void setFoo(Foo aFoo){\n  Foo old = this.foo;\n  this.foo = aFoo;\n  changeSupport.firePropertyChange("foo", old, aFoo);\n}\n</code></pre>\n\n<p>I recently stumbled across a blog that suggested a more terse implementation of this that makes the code a lot easier to write:</p>\n\n<pre><code>public void setFoo(Foo aFoo){\n  changeSupport.firePropertyChange("foo", this.foo, this.foo = aFoo);\n}\n</code></pre>\n\n<p>It actually simplified things to the point where I was able to adjust the setter template in Eclipse so the method gets created automatically.</p>\n'}, {'answer_id': 139379, 'author': 'Martin Spamer', 'author_id': 15527, 'author_profile': 'https://Stackoverflow.com/users/15527', 'pm_score': 3, 'selected': False, 'text': '<p><strong>String Parameterised Class Factory.</strong></p>\n\n<pre><code>Class.forName( className ).newInstance();\n</code></pre>\n\n<p><strong>Load a resource (property file, xml, xslt, image etc) from deployment jar file</strong>.</p>\n\n<pre><code>this.getClass().getClassLoader().getResourceAsStream( ... ) ;\n</code></pre>\n'}, {'answer_id': 142676, 'author': 'OscarRyz', 'author_id': 20654, 'author_profile': 'https://Stackoverflow.com/users/20654', 'pm_score': 3, 'selected': False, 'text': '<p>Something that really surprised me was the custom serialization mechanism.</p>\n\n<p>While these methods are <strong>private!!</strong>, they are "<em>mysteriously</em>" called by the JVM during object serialization.</p>\n\n<pre><code>private void writeObject(ObjectOutputStream out) throws IOException;\nprivate void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;\n</code></pre>\n\n<p>This way you can create your own custom serialization to make it more "whatever" (safe, fast, rare, easy etc. ) </p>\n\n<p>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.</p>\n\n<p>Here is an article.\n<a href="http://java.sun.com/developer/technicalArticles/Programming/serialization/" rel="nofollow noreferrer">http://java.sun.com/developer/technicalArticles/Programming/serialization/</a></p>\n'}, {'answer_id': 146121, 'author': 'oxbow_lakes', 'author_id': 16853, 'author_profile': 'https://Stackoverflow.com/users/16853', 'pm_score': 4, 'selected': False, 'text': '<p>You can declare a class in a method:</p>\n\n<pre><code>public Foo foo(String in) {\n    class FooFormat extends Format {\n        public Object parse(String s, ParsePosition pp) { // parse stuff }\n    }\n    return (Foo) new FooFormat().parse(in);\n\n}\n</code></pre>\n'}, {'answer_id': 148282, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Annotation Processing API from Java 6 looks very perspective for code generation and static code verification.</p>\n'}, {'answer_id': 169064, 'author': 'Allain Lalonde', 'author_id': 2443, 'author_profile': 'https://Stackoverflow.com/users/2443', 'pm_score': 6, 'selected': False, 'text': '<p><strong>final initialization can be postponed.</strong></p>\n\n<p>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:</p>\n\n<pre><code>public Object getElementAt(int index) {\n    final Object element;\n    if (index == 0) {\n         element = "Result 1";\n    } else if (index == 1) {\n         element = "Result 2";\n    } else {\n         element = "Result 3";\n    }\n    return element;\n}\n</code></pre>\n'}, {'answer_id': 170999, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 175511, 'author': 'Bill K', 'author_id': 12943, 'author_profile': 'https://Stackoverflow.com/users/12943', 'pm_score': 5, 'selected': False, 'text': "<p>Java processing does a neat trick on variable definition if you do not use a default initializer.</p>\n\n<pre>\n{\n   int x;\n\n   if(whatever)\n      x=1;\n\n   if(x == 1)\n      ...\n}\n</pre>\n\n<p>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:</p>\n\n<pre>\nint x=0;\nString s=null;\n</pre>\n\n<p>to be a bad pattern since it blocks this helpful checking.</p>\n\n<p>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.</p>\n"}, {'answer_id': 229899, 'author': 'Hans-Peter Störr', 'author_id': 21499, 'author_profile': 'https://Stackoverflow.com/users/21499', 'pm_score': 3, 'selected': False, 'text': '<p>You can access final local variables and parameters in initialization blocks and methods of local classes. Consider this:</p>\n\n<pre><code>    final String foo = "42";\n    new Thread() {\n        public void run() {\n             dowhatever(foo);\n        }\n    }.start();\n</code></pre>\n\n<p>A bit like a closure, isn\'t it?</p>\n'}, {'answer_id': 238827, 'author': 'Jack Leow', 'author_id': 31506, 'author_profile': 'https://Stackoverflow.com/users/31506', 'pm_score': 5, 'selected': False, 'text': '<p>The value of:</p>\n\n<pre><code>new URL("http://www.yahoo.com").equals(new URL("http://209.191.93.52"))\n</code></pre>\n\n<p>is <code>true</code>.</p>\n\n<p>(From Java Puzzlers)</p>\n'}, {'answer_id': 238837, 'author': 'Jack Leow', 'author_id': 31506, 'author_profile': 'https://Stackoverflow.com/users/31506', 'pm_score': 6, 'selected': False, 'text': '<p>A couple of people have posted about instance initializers, here\'s a good use for it:</p>\n\n<pre><code>Map map = new HashMap() {{\n    put("a key", "a value");\n    put("another key", "another value");\n}};\n</code></pre>\n\n<p>Is a quick way to initialize maps if you\'re just doing something quick and simple.</p>\n\n<p>Or using it to  create a   quick swing frame prototype:</p>\n\n<pre><code>JFrame frame = new JFrame();\n\nJPanel panel = new JPanel(); \n\npanel.add( new JLabel("Hey there"){{ \n    setBackground(Color.black);\n    setForeground( Color.white);\n}});\n\npanel.add( new JButton("Ok"){{\n    addActionListener( new ActionListener(){\n        public void actionPerformed( ActionEvent ae ){\n            System.out.println("Button pushed");\n        }\n     });\n }});\n\n\n frame.add( panel );\n</code></pre>\n\n<p>Of course it can be abused:</p>\n\n<pre><code>    JFrame frame = new JFrame(){{\n         add( new JPanel(){{\n               add( new JLabel("Hey there"){{ \n                    setBackground(Color.black);\n                    setForeground( Color.white);\n                }});\n\n                add( new JButton("Ok"){{\n                    addActionListener( new ActionListener(){\n                        public void actionPerformed( ActionEvent ae ){\n                            System.out.println("Button pushed");\n                        }\n                     });\n                 }});\n        }});\n    }};\n</code></pre>\n'}, {'answer_id': 259287, 'author': 'Paul Wicks', 'author_id': 85, 'author_profile': 'https://Stackoverflow.com/users/85', 'pm_score': 7, 'selected': False, 'text': '<p>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</p>\n\n<pre><code>public void foo(String... bars) {\n   for (String bar: bars)\n      System.out.println(bar);\n}\n</code></pre>\n\n<p>bars is automatically converted to array of the specified type. Not a huge win, but a win nonetheless.</p>\n'}, {'answer_id': 284614, 'author': 'user24081', 'author_id': 24081, 'author_profile': 'https://Stackoverflow.com/users/24081', 'pm_score': 4, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 306721, 'author': 'Dan Vinton', 'author_id': 21849, 'author_profile': 'https://Stackoverflow.com/users/21849', 'pm_score': 2, 'selected': False, 'text': '<p><a href="http://en.wikipedia.org/wiki/SwingWorker" rel="nofollow noreferrer">SwingWorker</a> for easily managing user interface callbacks from background threads.</p>\n'}, {'answer_id': 321782, 'author': 'David Koelle', 'author_id': 2197, 'author_profile': 'https://Stackoverflow.com/users/2197', 'pm_score': 3, 'selected': False, 'text': "<p>Instances of the same class can access private members of other instances:</p>\n\n<pre><code>class Thing {\n  private int x;\n\n  public int addThings(Thing t2) {\n    return this.x + t2.x;  // Can access t2's private value!\n  }\n}\n</code></pre>\n"}, {'answer_id': 336346, 'author': 'Joe', 'author_id': 42276, 'author_profile': 'https://Stackoverflow.com/users/42276', 'pm_score': 2, 'selected': False, 'text': '<p>Apparently with some debug builds there is an option which dumps the native (JIT) assembly code from HotSpot: <a href="http://weblogs.java.net/blog/kohsuke/archive/2008/03/deep_dive_into.html" rel="nofollow noreferrer">http://weblogs.java.net/blog/kohsuke/archive/2008/03/deep_dive_into.html</a></p>\n\n<p>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.</p>\n'}, {'answer_id': 341823, 'author': 'stili', 'author_id': 20763, 'author_profile': 'https://Stackoverflow.com/users/20763', 'pm_score': 5, 'selected': False, 'text': '<p>My vote goes to <strong>java.util.concurrent</strong> 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.</p>\n\n<p>java.util.Timer and TimerTask may safely be put to rest.</p>\n\n<p>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.</p>\n\n<p>It reads a lot better than the usual someValue * 1000 or someValue / 1000.</p>\n'}, {'answer_id': 404567, 'author': 'Romain Guy', 'author_id': 298575, 'author_profile': 'https://Stackoverflow.com/users/298575', 'pm_score': 4, 'selected': False, 'text': '<p>The strictfp keyword. (I never saw it used in a real application though :)</p>\n\n<p>You can get the class for primitive types by using the following notation: int.class, \nfloat.class, etc. Very useful when doing reflection.</p>\n\n<p>Final arrays can be used to "return" values from anonymous inner classes (warning, useless example below):</p>\n\n<pre><code>final boolean[] result = new boolean[1];\nSwingUtilities.invokeAndWait(new Runnable() {\n  public void run() { result[0] = true; }\n});\n</code></pre>\n'}, {'answer_id': 457863, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 7, 'selected': False, 'text': "<p>Haven't seen anyone mention instanceof being implemented in such a way that checking for null is not necessary.</p>\n\n<p>Instead of:</p>\n\n<pre><code>if( null != aObject &amp;&amp; aObject instanceof String )\n{\n    ...\n}\n</code></pre>\n\n<p>just use:</p>\n\n<pre><code>if( aObject instanceof String )\n{\n    ...\n}\n</code></pre>\n"}, {'answer_id': 492663, 'author': 'grayger', 'author_id': 433078, 'author_profile': 'https://Stackoverflow.com/users/433078', 'pm_score': 1, 'selected': False, 'text': '<p>I enjoyed</p>\n\n<ol>\n<li><a href="http://java.sun.com/javase/6/docs/technotes/guides/javadoc/" rel="nofollow noreferrer">javadoc</a>\'s taglet and doclet that enable us to customize javadoc output.</li>\n<li><a href="http://java.sun.com/javase/6/docs/technotes/tools/" rel="nofollow noreferrer">JDK tools</a>: jstat, jstack etc.</li>\n</ol>\n'}, {'answer_id': 511975, 'author': 'Sarel Botha', 'author_id': 35264, 'author_profile': 'https://Stackoverflow.com/users/35264', 'pm_score': 3, 'selected': False, 'text': '<p>The next-generation Java plugin found in Java 1.6 Update 10 and later has some very neat features:</p>\n\n<ul>\n<li>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.</li>\n<li>Create separate class loaders or even separate JVM\'s for each applet.</li>\n<li>Specify the JVM version to use.</li>\n<li>Install partial Java kernels in cases where you only need a subset of the full Java libraries\' functionality.</li>\n<li>Better Vista support.</li>\n<li>Support (experimental) to drag an applet out of the browser and have it keep running when you navigate away.</li>\n</ul>\n\n<p>Many other things that are documented here: <a href="http://jdk6.dev.java.net/plugin2/" rel="noreferrer">http://jdk6.dev.java.net/plugin2/</a></p>\n\n<p>More from this release here: <a href="http://jdk6.dev.java.net/6u10ea.html" rel="noreferrer">http://jdk6.dev.java.net/6u10ea.html</a></p>\n'}, {'answer_id': 512216, 'author': 'Sarel Botha', 'author_id': 35264, 'author_profile': 'https://Stackoverflow.com/users/35264', 'pm_score': 3, 'selected': False, 'text': '<p>You can build a string sprintf-style using String.format().</p>\n\n<pre><code>String w = "world";\nString s = String.format("Hello %s %d", w, 3);\n</code></pre>\n\n<p>You can of course also use special specifiers to modify the output.</p>\n\n<p>More here: <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax" rel="nofollow noreferrer">http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax</a></p>\n'}, {'answer_id': 512368, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>with static imports you can do cool stuff like: </p>\n\n<pre><code>List&lt;String&gt; myList = list("foo", "bar");\nSet&lt;String&gt; mySet = set("foo", "bar");\nMap&lt;String, String&gt; myMap = map(v("foo", "2"), v("bar", "3"));\n</code></pre>\n'}, {'answer_id': 556664, 'author': 'youri', 'author_id': 16805, 'author_profile': 'https://Stackoverflow.com/users/16805', 'pm_score': 4, 'selected': False, 'text': '<p>I like the static import of methods.</p>\n\n<p>For example create the following util class:</p>\n\n<pre><code>package package.name;\n\npublic class util {\n\n     private static void doStuff1(){\n        //the end\n     }\n\n     private static String doStuff2(){\n        return "the end";\n     }\n\n}\n</code></pre>\n\n<p>Then use it like this.</p>\n\n<pre><code>import static package.name.util.*;\n\npublic class main{\n\n     public static void main(String[] args){\n          doStuff1(); // wee no more typing util.doStuff1()\n          System.out.print(doStuff2()); // or util.doStuff2()\n     }\n\n}\n</code></pre>\n\n<p><a href="http://en.wikipedia.org/wiki/Static_import" rel="nofollow noreferrer">Static Imports</a> works with any class, even Math...</p>\n\n<pre><code>import static java.lang.Math.*;\nimport static java.lang.System.out;\npublic class HelloWorld {\n    public static void main(String[] args) {\n        out.println("Hello World!");\n        out.println("Considering a circle with a diameter of 5 cm, it has:");\n        out.println("A circumference of " + (PI * 5) + "cm");\n        out.println("And an area of " + (PI * pow(5,2)) + "sq. cm");\n    }\n}\n</code></pre>\n'}, {'answer_id': 556756, 'author': 'chillitom', 'author_id': 56679, 'author_profile': 'https://Stackoverflow.com/users/56679', 'pm_score': 4, 'selected': False, 'text': '<p><strong>List.subList returns a view on the original list</strong></p>\n<p>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.</p>\n<p><strong>List subList(int fromIndex, int toIndex)</strong></p>\n<blockquote>\n<p>&quot;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:</p>\n<pre><code>       list.subList(from, to).clear();\n</code></pre>\n<p>Similar idioms may be constructed for indexOf and lastIndexOf, and all of the algorithms in the Collections class can be applied to a subList.&quot;</p>\n</blockquote>\n'}, {'answer_id': 556772, 'author': 'Rahel Lüthy', 'author_id': 57448, 'author_profile': 'https://Stackoverflow.com/users/57448', 'pm_score': 5, 'selected': False, 'text': '<p>i personally discovered <code>java.lang.Void</code> very late -- improves code readability in conjunction with generics, e.g. <code>Callable&lt;Void&gt;</code></p>\n'}, {'answer_id': 562852, 'author': 'Peter Lawrey', 'author_id': 57695, 'author_profile': 'https://Stackoverflow.com/users/57695', 'pm_score': 7, 'selected': False, 'text': '<p>You can use enums to implement an interface.</p>\n\n<pre><code>public interface Room {\n   public Room north();\n   public Room south();\n   public Room east();\n   public Room west();\n}\n\npublic enum Rooms implements Room {\n   FIRST {\n      public Room north() {\n         return SECOND;\n      }\n   },\n   SECOND {\n      public Room south() {\n         return FIRST;\n      }\n   }\n\n   public Room north() { return null; }\n   public Room south() { return null; }\n   public Room east() { return null; }\n   public Room west() { return null; }\n}\n</code></pre>\n\n<hr>\n\n<p>EDIT: Years later....</p>\n\n<p>I use this feature here</p>\n\n<pre><code>public enum AffinityStrategies implements AffinityStrategy {\n</code></pre>\n\n<p><a href="https://github.com/peter-lawrey/Java-Thread-Affinity/blob/master/src/main/java/vanilla/java/affinity/AffinityStrategies.java" rel="nofollow noreferrer">https://github.com/peter-lawrey/Java-Thread-Affinity/blob/master/src/main/java/vanilla/java/affinity/AffinityStrategies.java</a></p>\n\n<p>By using an interface, developers can define their own strategies. Using an <code>enum</code> means I can define a collection (of five) built in ones.</p>\n'}, {'answer_id': 574522, 'author': 'paulmurray', 'author_id': 63189, 'author_profile': 'https://Stackoverflow.com/users/63189', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n\n<pre><code>enum Foo1 implements Bar {}\nenum Foo2 implements Bar {}\n\nclass HelperClass {\n   static &lt;T extends Enum&lt;T&gt; &amp; Bar&gt; void fooBar(T the enum) {}\n}\n</code></pre>\n\n<p>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.</p>\n\n<pre><code>enum PrimaryColor {Red, Green, Blue;}\nenum PastelColor {Pink, HotPink, Rockmelon, SkyBlue, BabyBlue;}\n\nenum TransportMedium {Land, Sea, Air;}\nenum Vehicle {Car, Truck, BigBoat, LittleBoat, JetFighter, HotAirBaloon;}\n</code></pre>\n\n<p>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).</p>\n\n<p>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.</p>\n\n<pre><code>import java.util.EnumSet;\n\nimport javax.swing.JComponent;\n\npublic class zz extends JComponent {\n\n    public static void main(String[] args) {\n        System.out.println(PrimaryColor.Green + " " + ParentUtil.pctOf(PrimaryColor.Green) + "%");\n        System.out.println(TransportMedium.Air + " " + ParentUtil.pctOf(TransportMedium.Air) + "%");\n    }\n\n\n}\n\nclass ParentUtil {\n    private ParentUtil(){}\n    static &lt;P extends Enum&lt;P&gt; &amp; Parent&lt;P, C&gt;, C extends Enum&lt;C&gt; &amp; Child&lt;P, C&gt;&gt; //\n    float pctOf(P parent) {\n        return (float) parent.getChildren().size() / //\n                (float) EnumSet.allOf(parent.getChildClass()).size() //\n                * 100f;\n    }\n    public static &lt;P extends Enum&lt;P&gt; &amp; Parent&lt;P, C&gt;, C extends Enum&lt;C&gt; &amp; Child&lt;P, C&gt;&gt; //\n    EnumSet&lt;C&gt; loadChildrenOf(P p) {\n        EnumSet&lt;C&gt; cc = EnumSet.noneOf(p.getChildClass());\n        for(C c: EnumSet.allOf(p.getChildClass())) {\n            if(c.getParent() == p) {\n                cc.add(c);\n            }\n        }\n        return cc;\n    }\n}\n\ninterface Parent&lt;P extends Enum&lt;P&gt; &amp; Parent&lt;P, C&gt;, C extends Enum&lt;C&gt; &amp; Child&lt;P, C&gt;&gt; {\n    Class&lt;C&gt; getChildClass();\n\n    EnumSet&lt;C&gt; getChildren();\n}\n\ninterface Child&lt;P extends Enum&lt;P&gt; &amp; Parent&lt;P, C&gt;, C extends Enum&lt;C&gt; &amp; Child&lt;P, C&gt;&gt; {\n    Class&lt;P&gt; getParentClass();\n\n    P getParent();\n}\n\nenum PrimaryColor implements Parent&lt;PrimaryColor, PastelColor&gt; {\n    Red, Green, Blue;\n\n    private EnumSet&lt;PastelColor&gt;    children;\n\n    public Class&lt;PastelColor&gt; getChildClass() {\n        return PastelColor.class;\n    }\n\n    public EnumSet&lt;PastelColor&gt; getChildren() {\n        if(children == null) children=ParentUtil.loadChildrenOf(this);\n        return children;\n    }\n}\n\nenum PastelColor implements Child&lt;PrimaryColor, PastelColor&gt; {\n    Pink(PrimaryColor.Red), HotPink(PrimaryColor.Red), //\n    Rockmelon(PrimaryColor.Green), //\n    SkyBlue(PrimaryColor.Blue), BabyBlue(PrimaryColor.Blue);\n\n    final PrimaryColor  parent;\n\n    private PastelColor(PrimaryColor parent) {\n        this.parent = parent;\n    }\n\n    public Class&lt;PrimaryColor&gt; getParentClass() {\n        return PrimaryColor.class;\n    }\n\n    public PrimaryColor getParent() {\n        return parent;\n    }\n}\n\nenum TransportMedium implements Parent&lt;TransportMedium, Vehicle&gt; {\n    Land, Sea, Air;\n\n    private EnumSet&lt;Vehicle&gt;    children;\n\n    public Class&lt;Vehicle&gt; getChildClass() {\n        return Vehicle.class;\n    }\n\n    public EnumSet&lt;Vehicle&gt; getChildren() {\n        if(children == null) children=ParentUtil.loadChildrenOf(this);\n        return children;\n    }\n}\n\nenum Vehicle implements Child&lt;TransportMedium, Vehicle&gt; {\n    Car(TransportMedium.Land), Truck(TransportMedium.Land), //\n    BigBoat(TransportMedium.Sea), LittleBoat(TransportMedium.Sea), //\n    JetFighter(TransportMedium.Air), HotAirBaloon(TransportMedium.Air);\n\n    private final TransportMedium   parent;\n\n    private Vehicle(TransportMedium parent) {\n        this.parent = parent;\n    }\n\n    public Class&lt;TransportMedium&gt; getParentClass() {\n        return TransportMedium.class;\n    }\n\n    public TransportMedium getParent() {\n        return parent;\n    }\n}\n</code></pre>\n'}, {'answer_id': 766774, 'author': 'David Plumpton', 'author_id': 16709, 'author_profile': 'https://Stackoverflow.com/users/16709', 'pm_score': 3, 'selected': False, 'text': '<p>Read "Java Puzzlers" by Joshua Bloch and you will be both enlightened and horrified.</p>\n'}, {'answer_id': 851055, 'author': 'David Plumpton', 'author_id': 16709, 'author_profile': 'https://Stackoverflow.com/users/16709', 'pm_score': 3, 'selected': False, 'text': '<p>Source code URLs. E.g. here is some legal java source code:</p>\n\n<pre><code>http://google.com\n</code></pre>\n\n<p>(Yes, it was in Java Puzzlers. I laughed...)</p>\n'}, {'answer_id': 945115, 'author': 'Huxi', 'author_id': 115167, 'author_profile': 'https://Stackoverflow.com/users/115167', 'pm_score': 3, 'selected': False, 'text': '<p>People are sometimes a bit surprised when they realize that it\'s possible to call private methods and access/change private fields using reflection...</p>\n\n<p>Consider the following class:</p>\n\n<pre><code>public class Foo {\n    private int bar;\n\n    public Foo() {\n        setBar(17);\n    }\n\n    private void setBar(int bar) {\n        this.bar=bar;\n    }\n\n    public int getBar() {\n        return bar;\n    }\n\n    public String toString() {\n        return "Foo[bar="+bar+"]";\n    }\n}\n</code></pre>\n\n<p>Executing this program...</p>\n\n<pre><code>import java.lang.reflect.*;\n\npublic class AccessibleExample {\n    public static void main(String[] args)\n        throws NoSuchMethodException,IllegalAccessException, InvocationTargetException, NoSuchFieldException {\n        Foo foo=new Foo();\n        System.out.println(foo);\n\n        Method method=Foo.class.getDeclaredMethod("setBar", int.class);\n        method.setAccessible(true);\n        method.invoke(foo, 42);\n\n        System.out.println(foo);\n        Field field=Foo.class.getDeclaredField("bar");\n        field.setAccessible(true);\n        field.set(foo, 23);\n        System.out.println(foo);\n    }\n}\n</code></pre>\n\n<p>...will yield the following output:</p>\n\n<pre><code>Foo[bar=17]\nFoo[bar=42]\nFoo[bar=23]\n</code></pre>\n'}, {'answer_id': 949397, 'author': 'AaronG', 'author_id': 86001, 'author_profile': 'https://Stackoverflow.com/users/86001', 'pm_score': 4, 'selected': False, 'text': '<p>Part feature, part bother: Java\'s String handling to make it \'appear\' a native Type (use of operators on them, +, +=)</p>\n\n<p>Being able to write:</p>\n\n<pre><code>String s = "A";\ns += " String"; // so s == "A String"\n</code></pre>\n\n<p>is very convenient, but is simply syntactic sugar for (ie gets compiled to):</p>\n\n<pre><code>String s = new String("A");\ns = new StringBuffer(s).append(" String").toString();\n</code></pre>\n\n<p>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.</p>\n\n<p>A loop such as:</p>\n\n<pre><code>String s = "";\nfor (int i = 0 ; i &lt; 1000 ; ++i)\n  s += " " + i; // Really an Object instantiation &amp; 3 method invocations!\n</code></pre>\n\n<p>can (should) be rewritten in your code as:</p>\n\n<pre><code>StringBuilder buf = new StringBuilder(); // Empty buffer\nfor (int i = 0 ; i &lt; 1000 ; ++i)\n  buf.append(\' \').append(i); // Cut out the object instantiation &amp; reduce to 2 method invocations\nString s = buf.toString();\n</code></pre>\n\n<p>and will run approximately 80+% faster than the original loop!\n(up to 180% on some benchmarks I have run)</p>\n'}, {'answer_id': 983366, 'author': 'Peter Lawrey', 'author_id': 57695, 'author_profile': 'https://Stackoverflow.com/users/57695', 'pm_score': 5, 'selected': False, 'text': '<p>Perhaps the most surprising hidden feature is the sun.misc.Unsafe class.</p>\n\n<p><a href="http://www.docjar.com/html/api/ClassLib/Common/sun/misc/Unsafe.java.html" rel="nofollow noreferrer">http://www.docjar.com/html/api/ClassLib/Common/sun/misc/Unsafe.java.html</a></p>\n\n<p>You can;</p>\n\n<ul>\n<li>Create an object without calling a constructor.</li>\n<li>Throw any exception even Exception without worrying about throws clauses on methods. (There are other way to do this I know)</li>\n<li>Get/set randomly accessed fields in an object without using reflection.</li>\n<li>allocate/free/copy/resize a block of memory which can be long (64-bit) in size.</li>\n<li>Obtain the location of fields in an object or static fields in a class.</li>\n<li>independently lock and unlock an object lock. (like synchronize without a block)</li>\n<li>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)</li>\n</ul>\n\n<p>BTW: Incorrect use of this class will kill the JVM. I don\'t know which JVMs support this class so its not portable.</p>\n'}, {'answer_id': 1025199, 'author': 'Ron', 'author_id': 61572, 'author_profile': 'https://Stackoverflow.com/users/61572', 'pm_score': 6, 'selected': False, 'text': '<p>You can define an anonymous subclass and directly call a method on it even if it implements no interfaces.</p>\n\n<pre><code>new Object() {\n  void foo(String s) {\n    System.out.println(s);\n  }\n}.foo("Hello");\n</code></pre>\n'}, {'answer_id': 1025306, 'author': 'Dave Jarvis', 'author_id': 59087, 'author_profile': 'https://Stackoverflow.com/users/59087', 'pm_score': 3, 'selected': False, 'text': '<p>An optimization trick that makes your code easier to maintain and less susceptible to a concurrency bug.</p>\n\n<pre><code>public class Slow {\n  /** Loop counter; initialized to 0. */\n  private long i;\n\n  public static void main( String args[] ) {\n    Slow slow = new Slow();\n\n    slow.run();\n  }\n\n  private void run() {\n    while( i++ &lt; 10000000000L )\n      ;\n  }\n}\n</code></pre>\n\n<p>$ time java Slow<br />\nreal    0m15.397s<br />\n$ time java Slow<br />\nreal    0m20.012s<br />\n$ time java Slow<br />\nreal    0m18.645s<br /></p>\n\n<p><strong>Average: 18.018s</strong></p>\n\n<pre><code>public class Fast {\n  /** Loop counter; initialized to 0. */\n  private long i;\n\n  public static void main( String args[] ) {\n    Fast fast = new Fast();\n\n    fast.run();\n  }\n\n  private void run() {\n    long i = getI();\n\n    while( i++ &lt; 10000000000L )\n      ;\n\n    setI( i );\n  }\n\n  private long setI( long i ) {\n    this.i = i;\n  }\n\n  private long getI() {\n    return this.i;\n  }\n}\n</code></pre>\n\n<p>$ time java Fast<br />\nreal    0m12.003s<br />\n$ time java Fast<br />\nreal    0m9.840s<br />\n$ time java Fast<br />\nreal    0m9.686s<br /></p>\n\n<p><strong>Average: 10.509s</strong></p>\n\n<p>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).</p>\n\n<p>Another advantage to this technique (always using accessors) is that it eliminates a potential bug in the <strong>Slow</strong> class. If a second thread were to continually reset the value of <strong>i</strong> to 0 (by calling <code>slow.setI( 0 )</code>, for example), the <strong>Slow</strong> class could never end its loop. Calling the accessor and using a local variable eliminates that possibility.</p>\n\n<p>Tested using J2SE 1.6.0_13 on Linux 2.6.27-14.</p>\n'}, {'answer_id': 1027744, 'author': 'Nat', 'author_id': 99389, 'author_profile': 'https://Stackoverflow.com/users/99389', 'pm_score': 0, 'selected': False, 'text': '<p>Java Bean property accessor methods do <em>not</em> have to start with "get" and "set".  </p>\n\n<p>Even Josh Bloch gets this wrong in Effective Java.</p>\n'}, {'answer_id': 1191782, 'author': 'Peter Recore', 'author_id': 119365, 'author_profile': 'https://Stackoverflow.com/users/119365', 'pm_score': 4, 'selected': False, 'text': '<p>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:</p>\n\n<p><a href="http://garbagecollected.org/2008/04/06/dollarmaps/" rel="nofollow noreferrer">http://garbagecollected.org/2008/04/06/dollarmaps/</a></p>\n'}, {'answer_id': 1276933, 'author': 'Ivan Tarasov', 'author_id': 110225, 'author_profile': 'https://Stackoverflow.com/users/110225', 'pm_score': 3, 'selected': False, 'text': '<p>It has already been <a href="https://stackoverflow.com/questions/15496/hidden-features-of-java/404567#404567">mentioned</a> that a final array can be used to pass a variable out of the anonymous inner classes.</p>\n\n<p>Another, arguably better and less ugly approach though is to use AtomicReference (or AtomicBoolean/AtomicInteger/…) class from java.util.concurrent.atomic package.</p>\n\n<p>One of the benefits in doing so is that these classes also provide such methods as <code>compareAndSet</code>, which may be useful if you\'re creating several threads which can modify the same variable.</p>\n\n<hr>\n\n<p>Another useful related pattern:</p>\n\n<pre><code>final AtomicBoolean dataMsgReceived = new AtomicBoolean(false);\nfinal AtomicReference&lt;Message&gt; message = new AtomicReference&lt;Message&gt;();\nwithMessageHandler(new MessageHandler() {\n    public void handleMessage(Message msg) {\n         if (msg.isData()) {\n             synchronized (dataMsgReceived) {\n                 message.set(msg);\n                 dataMsgReceived.set(true);\n                 dataMsgReceived.notifyAll();\n             }\n         }\n    }\n}, new Interruptible() {\n    public void run() throws InterruptedException {\n        synchronized (dataMsgReceived) {\n            while (!dataMsgReceived.get()) {\n                dataMsgReceived.wait();\n            }\n        }\n    }\n});\n</code></pre>\n\n<p>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.</p>\n\n<p><code>waitMessageHandler(…)</code> above is yet another useful pattern: it sets up a handler somewhere, then starts executing the <em>Interruptible</em> which may throw an exception, and then removes the handler in the finally block, like so:</p>\n\n<pre><code>private final AtomicReference&lt;MessageHandler&gt; messageHandler = new AtomicReference&lt;MessageHandler&gt;();\npublic void withMessageHandler(MessageHandler handler, Interruptible logic) throws InterruptedException {\n    synchronized (messageHandler) {\n        try {\n            messageHandler.set(handler);\n            logic.run();\n        } finally {\n            messageHandler.set(null);\n        }\n    }\n}\n</code></pre>\n\n<p>Here I assume that the <strong>messageHandler</strong>\'s (if it\'s not null) <code>handleMessage(…)</code> method is called by another thread when a message is received. <strong>messageHandler</strong> must not be simply of <em>MessageHandler</em> type: that way you will synchronize on a changing variable, which is clearly a bug.</p>\n\n<p>Of course, it doesn\'t need to be <em>InterruptedException</em>, it could be something like <em>IOException</em>, or whatever makes sense in a particular piece of code.</p>\n'}, {'answer_id': 1305163, 'author': 'sibnick', 'author_id': 159923, 'author_profile': 'https://Stackoverflow.com/users/159923', 'pm_score': 3, 'selected': False, 'text': '<p>Comma &amp; array. It is legal syntax: String s[] = {<br/>\n "123" , <br/>\n "234" <strong>,</strong><br/>\n};</p>\n'}, {'answer_id': 1305616, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Most people does not know they can clone an array.</p>\n\n<pre><code>int[] arr = {1, 2, 3};\nint[] arr2 = arr.clone();\n</code></pre>\n'}, {'answer_id': 1674342, 'author': 'Lastnico', 'author_id': 201554, 'author_profile': 'https://Stackoverflow.com/users/201554', 'pm_score': 3, 'selected': False, 'text': '<p>Use <code>StringBuilder</code> instead of <code>StringBuffer</code> when you don\'t need synchronized management included in <code>StringBuilder</code>. It will increase the performance of your application.</p>\n\n<p>Improvements for Java 7 would be even better than any hidden Java features:</p>\n\n<ul>\n<li><strong>Diamond syntax:</strong> <a href="http://mail.openjdk.java.net/pipermail/coin-dev/2009-February/000009.html" rel="nofollow noreferrer">Link</a></li>\n</ul>\n\n<p>Don\'t use those infinite &lt;> syntax at instanciation:</p>\n\n<pre><code>Map&lt;String, List&lt;String&gt;&gt; anagrams = new HashMap&lt;String, List&lt;String&gt;&gt;();\n\n// Can now be replaced with this:\n\nMap&lt;String, List&lt;String&gt;&gt; anagrams = new HashMap&lt;&gt;();\n</code></pre>\n\n<ul>\n<li><strong>Strings in switch:</strong> <a href="http://mail.openjdk.java.net/pipermail/coin-dev/2009-February/000001.html" rel="nofollow noreferrer">Link</a></li>\n</ul>\n\n<p>Use String in switch, instead of old-C int:</p>\n\n<pre><code>String s = "something";\nswitch(s) {\n case "quux":\n    processQuux(s);\n    // fall-through\n\n  case "foo":\n  case "bar":\n    processFooOrBar(s);\n    break;\n\n  case "baz":\n     processBaz(s);\n    // fall-through\n\n  default:\n    processDefault(s);\n    break;\n}\n</code></pre>\n\n<ul>\n<li><strong>Automatic Resource Management</strong> <a href="http://mail.openjdk.java.net/pipermail/coin-dev/2009-February/000011.html" rel="nofollow noreferrer">Link</a></li>\n</ul>\n\n<p>This old code:</p>\n\n<pre><code>static void copy(String src, String dest) throws IOException {\n    InputStream in = new FileInputStream(src);\n    try {\n        OutputStream out = new FileOutputStream(dest);\n        try {\n            byte[] buf = new byte[8 * 1024];\n            int n;\n            while ((n = in.read(buf)) &gt;= 0)\n                out.write(buf, 0, n);\n        } finally {\n            out.close();\n        }\n    } finally {\n        in.close();\n    }\n}\n</code></pre>\n\n<p>can now be replaced by this much simpler code:</p>\n\n<pre><code>static void copy(String src, String dest) throws IOException {\n    try (InputStream in = new FileInputStream(src);\n            OutputStream out = new FileOutputStream(dest)) {\n        byte[] buf = new byte[8192];\n        int n;\n        while ((n = in.read(buf)) &gt;= 0)\n            out.write(buf, 0, n);\n    }\n}\n</code></pre>\n'}, {'answer_id': 1804983, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>You can switch(this) inside method definitions of enum classes.  Made me shout "whut!" loudly when I discovered that this actually works.</p>\n'}, {'answer_id': 1805139, 'author': 'Jonathan Locke', 'author_id': 1096108, 'author_profile': 'https://Stackoverflow.com/users/1096108', 'pm_score': 3, 'selected': False, 'text': "<p>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.</p>\n\n<p>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.</p>\n\n<p>CopyOnWriteArrayList might be unknown to some, and Future represents an interesting way to abstract multithreaded result access.</p>\n\n<p>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.</p>\n\n<p>Although TimeUnit is perhaps better than long, I prefer Wicket's Duration class.</p>\n"}, {'answer_id': 1805211, 'author': 'Jonathan Locke', 'author_id': 1096108, 'author_profile': 'https://Stackoverflow.com/users/1096108', 'pm_score': 4, 'selected': False, 'text': '<p>Oh, I almost forgot this little gem. Try this on any running java process:</p>\n\n<p>jmap -histo:live PID</p>\n\n<p>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.</p>\n'}, {'answer_id': 1807455, 'author': 'kcak11', 'author_id': 218432, 'author_profile': 'https://Stackoverflow.com/users/218432', 'pm_score': 4, 'selected': False, 'text': '<p>A feature with which you can display splash screens for your Java Console Based Applications.</p>\n\n<p>Use the command line tool <code>java</code> or <code>javaw</code> with the option <code>-splash</code></p>\n\n<p>eg:</p>\n\n<pre><code>java -splash:C:\\myfolder\\myimage.png -classpath myjarfile.jar com.my.package.MyClass\n</code></pre>\n\n<p>the content of <code>C:\\myfolder\\myimage.png</code> will be displayed at the center of your screen, whenever you execute the class "com.my.package.MyClass"</p>\n'}, {'answer_id': 1834084, 'author': 'Devon_C_Miller', 'author_id': 98811, 'author_profile': 'https://Stackoverflow.com/users/98811', 'pm_score': 5, 'selected': False, 'text': '<p>When working in Swing I like the hidden <kbd>Ctrl</kbd> - <kbd>Shift</kbd> - <kbd>F1</kbd> feature.</p>\n\n<p>It dumps the component tree of the current window.<br>\n(Assuming you have not bound that keystroke to something else.)</p>\n'}, {'answer_id': 1838200, 'author': 'fastcodejava', 'author_id': 184730, 'author_profile': 'https://Stackoverflow.com/users/184730', 'pm_score': -1, 'selected': False, 'text': '<p>Surprises me that an interface can extend multiple interfaces but class can extend only one class.</p>\n'}, {'answer_id': 1859579, 'author': 'crowne', 'author_id': 97745, 'author_profile': 'https://Stackoverflow.com/users/97745', 'pm_score': 7, 'selected': False, 'text': '<p>Classpath wild cards since Java 6.</p>\n\n<pre><code>java -classpath ./lib/* so.Main\n</code></pre>\n\n<p>Instead of</p>\n\n<pre><code>java -classpath ./lib/log4j.jar:./lib/commons-codec.jar:./lib/commons-httpclient.jar:./lib/commons-collections.jar:./lib/myApp.jar so.Main\n</code></pre>\n\n<p>See <a href="http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html" rel="nofollow noreferrer">http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html</a></p>\n'}, {'answer_id': 1918613, 'author': 'SRG', 'author_id': 195463, 'author_profile': 'https://Stackoverflow.com/users/195463', 'pm_score': 5, 'selected': False, 'text': '<p><a href="http://java.sun.com/developer/TechTips/2000/tt0711.html" rel="noreferrer">Shutdown Hooks.</a> 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 useful 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).</p>\n\n<p>Moreover it\'s pretty easy to set up.</p>\n\n<pre><code>            Runtime.getRuntime().addShutdownHook(new Thread() {\n                  public void run() {\n                      endApp();\n                  }\n            });;\n</code></pre>\n'}, {'answer_id': 2034744, 'author': 'stacker', 'author_id': 241590, 'author_profile': 'https://Stackoverflow.com/users/241590', 'pm_score': 3, 'selected': False, 'text': '<p>Identifiers can contain foreign language chars like umlauts:</p>\n\n<p>instead of writing:</p>\n\n<pre><code>String title="";\n</code></pre>\n\n<p>someone could write:</p>\n\n<pre><code>String Überschrift="";\n</code></pre>\n'}, {'answer_id': 2063863, 'author': 'nos', 'author_id': 126769, 'author_profile': 'https://Stackoverflow.com/users/126769', 'pm_score': 3, 'selected': False, 'text': '<p>Java 6 (from Sun) comes with an embedded JavaScrip interpreter.</p>\n\n<p><a href="http://java.sun.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html#jsengine" rel="noreferrer">http://java.sun.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html#jsengine</a></p>\n'}, {'answer_id': 2121023, 'author': 'Karussell', 'author_id': 194609, 'author_profile': 'https://Stackoverflow.com/users/194609', 'pm_score': 3, 'selected': False, 'text': "<p>Didn't read about this</p>\n\n<pre><code>Integer a = 1;\nInteger b = 1;\nInteger c = new Integer(1);\nInteger d = new Integer(1);\n\nInteger e = 128;\nInteger f = 128;\n\nassertTrue (a == b);   // again: this is true!\nassertFalse(e == f); // again: this is false!\nassertFalse(c == d);   // again: this is false!\n</code></pre>\n\n<p>read more about this by searching java's pool of integer (internal 'cache' from -128 to 127 for autoboxing) or look into Integer.valueOf</p>\n"}, {'answer_id': 2130784, 'author': 'finnw', 'author_id': 12048, 'author_profile': 'https://Stackoverflow.com/users/12048', 'pm_score': 2, 'selected': False, 'text': '<p>You can override a method and have the superclass constructor call it (this may come as a surprise to C++ programmers.)</p>\n\n<p><a href="https://stackoverflow.com/questions/2129647/exception-vs-throwable-in-java/2129655#2129655">Example</a></p>\n'}, {'answer_id': 2131355, 'author': 'Luigi R. Viggiano', 'author_id': 258289, 'author_profile': 'https://Stackoverflow.com/users/258289', 'pm_score': 5, 'selected': False, 'text': '<p>Here\'s my list.</p>\n\n<p>My favourite (and scariest) hidden feature is that you can throw checked exceptions from methods that are not declaring to throw anything.</p>\n\n<pre><code>import java.rmi.RemoteException;\n\nclass Thrower {\n    public static void spit(final Throwable exception) {\n        class EvilThrower&lt;T extends Throwable&gt; {\n            @SuppressWarnings("unchecked")\n            private void sneakyThrow(Throwable exception) throws T {\n                throw (T) exception;\n            }\n        }\n        new EvilThrower&lt;RuntimeException&gt;().sneakyThrow(exception);\n    }\n}\n\npublic class ThrowerSample {\n    public static void main( String[] args ) {\n        Thrower.spit(new RemoteException("go unchecked!"));\n    }\n}\n</code></pre>\n\n<hr>\n\n<p>Also you may like to know you can throw \'null\'...</p>\n\n<pre><code>public static void main(String[] args) {\n     throw null;\n}\n</code></pre>\n\n<hr>\n\n<p>Guess what this prints:</p>\n\n<pre><code>Long value = new Long(0);\nSystem.out.println(value.equals(0));\n</code></pre>\n\n<hr>\n\n<p>And, guess what this returns: </p>\n\n<pre><code>public int returnSomething() {\n    try {\n        throw new RuntimeException("foo!");\n    } finally {\n        return 0;\n    }\n}\n</code></pre>\n\n<p>the above should not surprise good developers.</p>\n\n<hr>\n\n<p>In Java you can declare an array in following valid ways:</p>\n\n<pre><code>String[] strings = new String[] { "foo", "bar" };\n// the above is equivalent to the following:\nString[] strings = { "foo", "bar" };\n</code></pre>\n\n<p>So following Java code is perfectly valid:</p>\n\n<pre><code>public class Foo {\n    public void doSomething(String[] arg) {}\n\n    public void example() {\n        String[] strings = { "foo", "bar" };\n        doSomething(strings);\n    }\n}\n</code></pre>\n\n<p>Is there any valid reason why, instead, the following code shouldn\'t be valid?</p>\n\n<pre><code>public class Foo {\n\n    public void doSomething(String[] arg) {}\n\n    public void example() {\n        doSomething({ "foo", "bar" });\n    }\n}\n</code></pre>\n\n<p>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. </p>\n'}, {'answer_id': 2294266, 'author': 'Dolph', 'author_id': 176741, 'author_profile': 'https://Stackoverflow.com/users/176741', 'pm_score': 5, 'selected': False, 'text': '<p>Every class file starts with the hex value <strong>0xCAFEBABE</strong> to identify it as valid JVM bytecode.</p>\n\n<p>(<a href="http://www.artima.com/insidejvm/whyCAFEBABE.html" rel="nofollow noreferrer">Explanation</a>)</p>\n'}, {'answer_id': 2372429, 'author': 'Yanamon', 'author_id': 282693, 'author_profile': 'https://Stackoverflow.com/users/282693', 'pm_score': 2, 'selected': False, 'text': "<p>You can add runtime checks of generic types using a <code>Class&lt;T&gt;</code> 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.</p>\n\n<pre><code>public interface SomeInterface {\n  void doSomething(Object o);\n}\npublic abstract class RuntimeCheckingTemplate&lt;T&gt; {\n  private Class&lt;T&gt; clazz;\n  protected RuntimeChecking(Class&lt;T&gt; clazz) {\n    this.clazz = clazz;\n  }\n\n  public void doSomething(Object o) {\n    if (clazz.isInstance(o)) {\n      doSomethingWithGeneric(clazz.cast(o));\n    } else {\n      // log it, do something by default, throw an exception, etc.\n    }\n  }\n\n  protected abstract void doSomethingWithGeneric(T t);\n}\n\npublic class ClassThatWorksWithStrings extends RuntimeCheckingTemplate&lt;String&gt; {\n  public ClassThatWorksWithStrings() {\n     super(String.class);\n  }\n\n  protected abstract void doSomethingWithGeneric(T t) {\n    // Do something with the generic and know that a runtime exception won't occur \n    // because of a wrong type\n  }\n}\n</code></pre>\n"}, {'answer_id': 2607251, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': -1, 'selected': False, 'text': '<p>I was surprised when I first noticed the Ternary-Operator which equals a simple if-then-else statement:</p>\n\n<pre><code>minVal = (a &lt; b) ? a : b;\n</code></pre>\n'}, {'answer_id': 3004405, 'author': 'mbenturk', 'author_id': 210705, 'author_profile': 'https://Stackoverflow.com/users/210705', 'pm_score': 3, 'selected': False, 'text': '<p>I can add Scanner object. It is the best for parsing.  </p>\n\n<pre><code>String input = "1 fish 2 fish red fish blue fish";\nScanner s = new Scanner(input).useDelimiter("\\\\s*fish\\\\s*");\nSystem.out.println(s.nextInt());\nSystem.out.println(s.nextInt());\nSystem.out.println(s.next());\nSystem.out.println(s.next());\ns.close();\n</code></pre>\n'}, {'answer_id': 3089101, 'author': 'OscarRyz', 'author_id': 20654, 'author_profile': 'https://Stackoverflow.com/users/20654', 'pm_score': 4, 'selected': False, 'text': '<p>You can define and invoke methods on anonymous inner classes.</p>\n\n<p>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:</p>\n\n<pre><code>(new Object() {\n    public String someMethod(){ \n        return "some value";\n    }\n}).someMethod();\n</code></pre>\n\n<p>Probably is not very common because it not very useful either, you can call the method it <strong>only</strong> when you define it ( or via reflection ) </p>\n'}, {'answer_id': 3130075, 'author': 'Jason Wang', 'author_id': 144282, 'author_profile': 'https://Stackoverflow.com/users/144282', 'pm_score': 4, 'selected': False, 'text': '<p>This is not really a hidden feature but it did give me a big surprise when I saw this compiled fine:</p>\n\n<pre><code>public int aMethod(){\n    http://www.google.com\n    return 1;\n}\n</code></pre>\n\n<p>the reason why it compiles is that the line <a href="http://www.google.com" rel="noreferrer">http://www.google.com</a> the "http:" part is treated by the compiler as a label and the rest of the line is a comment.</p>\n\n<p>So, if you want to write some bizzare code  (or obfuscated code), just put alot of http addresses there. ;-)</p>\n'}, {'answer_id': 3147440, 'author': 'st0le', 'author_id': 216517, 'author_profile': 'https://Stackoverflow.com/users/216517', 'pm_score': 4, 'selected': False, 'text': '<p>The C-Style printf() :)</p>\n\n<pre><code>System.out.printf("%d %f %.4f", 3,Math.E,Math.E);\n</code></pre>\n\n<p>Output:\n3 2.718282 2.7183</p>\n\n<p>Binary Search (and it\'s return value)</p>\n\n<pre><code>int[] q = new int[] { 1,3,4,5};\nint position = Arrays.binarySearch(q, 2);\n</code></pre>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>I thinks its pretty nifty... :)</p>\n'}, {'answer_id': 3181454, 'author': 'OscarRyz', 'author_id': 20654, 'author_profile': 'https://Stackoverflow.com/users/20654', 'pm_score': 5, 'selected': False, 'text': '<p>Not so hidden, but interesting.</p>\n\n<p>You can have a "Hello, world" without main method ( it throws NoSuchMethodError thought ) </p>\n\n<p>Originally posted by  RusselW on <a href="https://stackoverflow.com/questions/1995113/strangest-language-feature/3161298#3161298">Strangest language feature</a></p>\n\n<pre><code>public class WithoutMain {\n    static {\n        System.out.println("Look ma, no main!!");\n        System.exit(0);\n    }\n}\n\n$ java WithoutMain\nLook ma, no main!!\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/15496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/486/']