12 Java Snippets you won’t believe actually compile

“Does that really compile?” you might wonder not just once, but twelve times in a row – while reading this post about interesting, but valid Java syntax.

Our naming conventions have become quite complex recently
Our naming conventions have become quite complex recently

Introduction

I am currently preparing for a Java certification using two books called “OCA Java SE 7 Programmer I Certification Guide” and “OCP Java SE 7 Programmer II Certification Guide” both written by Mala Gupta. Although I would not describe myself as inexperienced in dealing with Java, I had quite a few moments of astonishment about weird-looking syntax which actually compiles and works in Java. Thus, I decided to share some of the highlights with you in the form of twelve little snippets.

So fire up eclipse (or your preferred IDE / text editor) as you might be tempted to verify and play around with some of those snippets. For your convenience, they are also available on GitHub. Get ready – here they come!

Oh – if you have any similar snippets: Share them in the comments at the end of this article!

0. Naming variables using Unicode

Let’s start with a simple one (also shown in the screenshot above as the text below looks less impressive due to the code formatting plugin):

class Foo {
   //Generated using http://www.eeemo.net/
   public static void main(String[] args) {
      String $h͉̠͇̹̖̼̖͈̬̘͕͎͈̬̺̺̯̅̃ͯ̈̂̐̿̍̌͑ͩ̑ͦ̿͡e̛̛̹̞͚̭̻͇̰̟͙̱͉̣̼̻̝͕̭ͯͦ͌̒̽̐l̸̵̷̛͍̬͎̲̲̹̙͙̞͚̲̭̫̬ͭ͗̒ͯ̈́ͣ͂ͧ̌̿ͮ̈́ͫ̽ͩ̈͞ṗ̨̟̰͈̹̗͖̰̙͉͎̗͓̬̳ͤ͒ͣ̓̂͛͑̑ͦͮ̅͆̈ͥ̈́́̈̋́̕͞ = "Test"; 

      System.out.println($h͉̠͇̹̖̼̖͈̬̘͕͎͈̬̺̺̯̅̃ͯ̈̂̐̿̍̌͑ͩ̑ͦ̿͡e̛̛̹̞͚̭̻͇̰̟͙̱͉̣̼̻̝͕̭ͯͦ͌̒̽̐l̸̵̷̛͍̬͎̲̲̹̙͙̞͚̲̭̫̬ͭ͗̒ͯ̈́ͣ͂ͧ̌̿ͮ̈́ͫ̽ͩ̈͞ṗ̨̟̰͈̹̗͖̰̙͉͎̗͓̬̳ͤ͒ͣ̓̂͛͑̑ͦͮ̅͆̈ͥ̈́́̈̋́̕͞);

      String € = "EUR";
      System.out.println(€);
   }
}

As you might know, Java allows

an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign “$”, or the underscore character “_” [as a legal identifier for a variable’s name]”
Oracle

This also includes diacritics. Usually, a letter in a regular alphabet might have maybe one or two diacritics attached, but technically, there is no such limitation. Thus, the variable name is valid (make sure to save the file as UTF-8, however). As it happens, not only the dollar sign is a valid identifier, but also the Euro sign and other currency signs.

If you want to impress your coworkers with your Unicode skills, you can head to the Zalgo text generator to give your email or private message a special touch.

1. Using Class.this and Class.super

public class Foo {
   private int var;

   class Bar {
      void doSomething() {
         System.out.println(Foo.this.var);
         System.out.println(Foo.super.toString());
      }
   }
}

This one is actually quite handy and one of the few ones you might actually end up using in production code. In order to access the members of an outer class from within a nested class, you can use the Class.this and Class.super keywords. Especially, if you need access to the instance of the outer class itself or you are trying to access a hidden method, this syntax will allow you to. Also, you can use it to distinguish between members of the outer class and members of the inner class sharing the same name.

Nevertheless, many programmers have not seen this before and might question the correctness of the code at first. See Nested Classes for more information.

2. Writing a class inside a method

public class Foo {
   public void doSomething() {
      System.out.print("Hello ");

      class Bar {
         Bar() {
            System.out.println("World");
         }
      }

      new Bar();
   }

   public static void main(String[] args) {
      new Foo().doSomething();
   }
}

Using anonymous classes inside methods is very common in Java, particularly when dealing with event handlers of user interfaces or other types of callbacks. But did you know that you can also define so-called local classes inside methods? Now you do!

3. Using modifier keywords before the visibility specification

public class Foo {
   synchronized strictfp final public void bar() {
      System.out.println("Hello world");
   }
   public static void main(String[] args) {
      new Foo().bar();
   }
}

Unlike other languages in the C-family, Java actually allows to place method modifiers in front of the visibility modifier. Very easy to overlook in mean tests or interview questions! For added effect, I included a stunning number of three different ones in my example:

  1. synchronized for acquiring a monitor
  2. strictfp forcing strict floating point behaviour
  3. final to prevent overriding and hiding

4. Declaring new exceptions on subclasses

interface Foo {
   void baz();
   void bat();
}

class Bar implements Foo {
   public void baz() /*throws FileNotFoundException*/ {
   }

   public void bat() throws NullPointerException, NoSuchElementException, UnsupportedOperationException  {
   }
}

When implementing an interface, it is generally required that the “exception specification of the subclass method is […] compatible with (i.e. […] a subset of) that of the superclass/interface method”. This can be verified by uncommenting the throws FileNotFoundException for baz which causes a compilation error: “Exception FileNotFoundException is not compatible with throws clause in Foo.baz()”.

Then why does the above code compile in its original form? Shouldn’t it cause the same compiler error? The answer is that the requirement only applies to checked exceptions. As NullPointerException, NoSuchElementException and UnsupportedOperationException are all unchecked exceptions, you do not even need to declare them. In fact, their declaration is ignored, thus causing no conflict regarding the exception specification.

5. Fun with enums

public enum Foo {
   A("C") {
      void doSomething() {
         System.out.println("A: " + this.var);
      }     
   },
   B("D") {
      void doSomething() {
         System.out.println("B: " + this.var);
      }
   };

   protected String var;

   Foo(String var) {
      this.var = var;
   }

   abstract void doSomething();

   public static void main(String[] args) {
      method(Foo.A);
      method(Foo.B);
   }

   static void method(Foo foo) {
      foo.doSomething();
   }
}

Enums in Java are much more flexible and powerful than their counterparts in other languages. Although you shouldn’t overdo it, some of those features are really useful. This enum comes packed with lots of interesting stuff:

  • A static method
  • An additional instance variable
  • A main method. Yep, that’s possible in Java.
  • A constructor which is being called by the members (note the lack of a new keyword)
  • An abstract method which is overridden by the members (in a syntax similar to anonymous classes)

6. Using initializer blocks (static and instance)

public class Foo {
    {
        System.out.print("1 ");
    }
    static {
        System.out.print("2 ");
    }
    Foo () {
        System.out.print("3 ");

    }
    {
        System.out.print("4 ");
    }
    static {
        System.out.print("5 ");
    }

    public static void main(String[] args) {
        new Foo();
    }
}

Upon first sight of an initializer block, I thought that someone had forgotten to put in the class name in front of it to make it a constructor. Then, I noticed that the class indeed did have a constructor. It turns out that Java allows you to define an arbitrary number of initializer blocks (both static and instance, i.e. non-static) for a class besides possible constructors. They are executed before any constructor in the order of which they appear (static ones before non-static ones). In case you are wondering: The output is “2 5 1 4 3”.

Neat, actually! I can’t understand why this feature is not used more widespread.

7. Calling a method on null

public class Foo {
    public static void doSomething() {
        System.out.print("Foo ");
    }

    public static void main(String[] args) {
        ((Foo)null).doSomething();
    }
}

Ok, this one is not about the compiler, it’s about running the code. But still, it’s the compiler which is responsible for the snippet above not throwing a NullPointerException as one might think at first.

Notice the static on the method definition? That’s the catch: Static methods are resolved at compile time in Java which means that the instance (which is null in this case) is never evaluated. Practically speaking, no polymorphism is shown for static methods. We can further illustrate this by extending our example:

class Derived extends Foo {
    public static void doSomething() {
        System.out.print("Derived ");       
    }
}

//...

Derived derived = new Derived();
Foo foo = derived;
derived.doSomething();
foo.doSomething();

Instead of calling the doSomething method in Derived as one might expect, the output is “Derived Foo”. Because the second call is done using a reference of type Foo and no polymorphism is employed as described, we end up in the implementation of Foo.

Did you know that? Well – I certainly didn’t think about it until a couple of weeks ago. This again shows why declaring two static methods with the same name inside a class hierarchy is a bad idea.

8. Calling new on an object

class Foo {
    class Bar {

    }
}

class Baz {
    public static void main(String[] args) {
        Foo foo = new Foo();
        //Foo.Bar bar = new Foo.Bar();
        Foo.Bar bar = foo.new Bar();
    }
}

In case you missed it: This snippet is about the foo.new Bar(); which is not a method call, but an invocation of the new operator on an existing object.

So what does it do? As a matter of fact, it does what the new operator always does: It initializes a new instance of a class. In this case, however, as we want to create an instance of the inner class Bar outside of its outer class, we need to use this syntax. Remember, an instance of an inner class is always bound to an instance of the outer class (unless the inner class is marked as static). For this reason, we can not create a Bar independently from a Foo instance (this is what the line which is commented out tries to do – results in the compiler error:

“No enclosing instance of type Foo is accessible. Must qualify the allocation with an enclosing instance of type Foo (e.g. x.new A() where x is an instance of Foo).”).

This syntax allows us to “connect” the Bar instance to an existing Foo instance.

9. Providing a generic constructor

class Foo {
    public <T> Foo(T t) {
        System.out.println(t);
    }

    public static void main(String[] args) {
        Foo foo1 = new Foo("Test");
        Foo foo2 = new Foo(42);
    }
}

You probably know how to create a generic method in Java. Still, you might not know about generic constructors which are also possible. Don’t ask me, though, why you might want to do that (if you have any idea – let me know in the comments!).

EDIT: As pointed out in the comments by Christian and fabienbk, this syntax is quite useful if you want to express constraints between constructor parameters, for example:

class Bar {
    public <T> Bar(Node<T> parent, T value) {

    }
}

//...

new Bar(new Node<String>("Hello World!"), "Test"); //Compiles sucessfully
new Bar(new Node<String>("Hello World!"), 42); //Compilation error

In addition, it also allows you to kind of use “anonymous” types for parameters by requiring multiple interfaces that a parameter needs to implement:

class Bar {
    public <T extends Comparable<T> & Serializable> Bar(T param) {

    }
}
class Baz {

}

//...

new Bar("Hello World!");  //Yep
new Bar(new Baz()); //Nope

10. Explicit specification of generic type parameters when calling a method

class Foo {
   public <T> void temp(T param) {
      System.out.println(param.getClass());
   }    

   public static void main(String[] args) {
      Foo foo = new Foo();
      foo.temp(42);
      foo.<Integer>temp(42);
   }
}

When calling a generic method, the Java compiler uses Type inference to determine the most suitable type to use as a type parameter. If – for some reason – the compiler is unable to find a suitable type or you disagree with its choice, you can manually specify the type parameter when calling a method: foo.<Integer>temp(42);.

Personally, I would rather explicitly cast the parameter to the desired type than using this syntax (foo.temp((Integer) 42); if I feel the need to state the type. And I can’t think of any disadvantage the latter version might have.

11. Explicitly specifying the type parameters of a generic constructor and the type itself

public class Foo<T> {
    public <T> Foo(T param) {
        System.out.println(param.getClass());
    }

    public static void main(String[] args) {
        //Foo<String> foo = new <String>Foo<>("Test");
        Foo<Integer> foo = new <String>Foo<Integer>("Test");
    }
}

What do you get if you combine the previous two inside of a generic class? This. Looks kind of strange, if you ask me…

Note that the line which is commented out does not compile causing the compiler error “Explicit type arguments cannot be used with ‘<>’ in an allocation expression” (At the time of writing, searching for this error message only yields 5 hits on Google!)

Bonus: Putting a URL directly into the code

public class Foo {  
    public static void main(String[] args) {
        http://www.journeyofcode.com
        System.out.print("Hello ");
        http://www.example.org
        System.out.print(" World!");
    }
}

Credits to UnspeakableEvil on Reddit for this one!

You can put URLs directly into the source code (at some locations, at least). Syntax highlighting in Eclipse quickly gives away, what is happening: The http: is interpreted as a label (which can be used to break out of nested loops) and everything behind is a comment.

Conclusion

I hope you enjoyed our little trip to the stranger parts of the Java syntax. Maybe you already knew about a couple of those. But maybe it’s even better if you have never encountered some of them before – that only means that you never had to experience truly horrible code which tried to incorporate them for some reason.

Again, feel free to share similar snippets in the comments and visit GitHub for the code!

  • fabienbk

    Hmmm, I think generic constructors allow to create type constraints between the parameters of the constructor. e.g new Foo(Bar.class, instanceOfBar)

    • Great point, thank you!
      I have updated the article correspondingly.

      • fabienbk

        Great article by the way. Hey, a fun thing to do with 6: the pseudo “double brace” operator, allowing to populate values in collections in a nifty one-liner:

        new HashMap() {{ put(“key”, “value”); put(“key2”, “value2”); }}

        • Nice one! It’s always amazing to see how some language features can be used in clever ways that actually benefit readability 🙂

          • Tomáš Záluský

            IMHO double braces are interesting as a trick but for practical usage I consider it as antipattern. For example, you cannot send such an instance via RMI (or Spring httpinvoker in our case) because the peer hasn’t the anonymous subclass. I prefer using Guava ImmutableMap.Builder.

          • Good point! In addition, the syntax might result in a memory leak as the anonymous class keeps a reference to the outer class.
            So it is probably right to call it an antipattern…

          • fabienbk

            Agreed. It’s for “clever one-liners”, not for serious code 🙂

  • Patrick

    I’ve used generic constructors (in scala) to build objects that are related (through inheritance). For instance,

    class Base { public Base(Data d) { return libraryThatBuildsWithData(d) }

    class Derived { public Derived(Data d) { return super(d) } // And many more of these

    Now all my derived classes can invoke the base constructor. Great for deserialization!

  • Christian

    You can use generic constructors to constrain variable types, e.g. public Constructor(final Key key, final T value), so that variables that need to share a common type can be forced to do so.

  • Kirill Rakhman

    Regarding #10: Generic parameters are useful if the method doesn’t have any parameters. One famous example is Collections.emptyList() which return a List and sometimes T cannot be inferred by the compiler automatically.

  • Juan Cruz Nores

    One I find puzzling is this one: http://pastebin.com/Hjy5HgP9 where you essentially define an anonymous type, and use it. Note that the instance cannot be extracted into a variable because there’s no way to refer to the type of the object, nevertheless it does have a type, and the compiler can access it, as long as it doesn’t have to explicitly name it.

  • The “named inner class” is called a “local class”

  • Stuart Marks

    How about the alternate array syntax, e.g. int[] foo; int bar[]; are both arrays of int. One can also apply this alternate array syntax to method return types. int[] foo() { return new int[5]; } and int bar()[] { return new int[5]; } are both methods returning arrays of int!

  • Peter Lawrey

    This contains a special unicode character 😉

    for (char c‮h = 0; c‮h < Character.MAX_VALUE; c‮h++)
    if (Character.isJavaIdentifierPart(c‮h) && !Character.isJavaIdentifierStart(c‮h))
    System.out.printf("%04x %n”, (int) c‮h, “” + c‮h);

    It prints all the unicode characters you can use in a variable. Some have zero width 😉

  • Great article, Java is an interesting and confusing language. I am working on the same exam. Thanks!

  • An0nym0usC0ward

    I’d expect the syntax in 7 do generate a compiler warning – something about static methods to be called on the class, instead of an instance.

  • KevinC

    I know it’s been two years, but something I came across and didn’t knew you could do in Java is this:

    u0070u0075u0062u006cu0069u0063u0020u0020u0020u0020
    u0063u006cu0061u0073u0073u0020u0055u0067u006cu0079
    u007bu0070u0075u0062u006cu0069u0063u0020u0020u0020
    u0020u0020u0020u0020u0073u0074u0061u0074u0069u0063
    u0076u006fu0069u0064u0020u006du0061u0069u006eu0028
    u0053u0074u0072u0069u006eu0067u005bu005du0020u0020
    u0020u0020u0020u0020u0061u0072u0067u0073u0029u007b
    u0053u0079u0073u0074u0065u006du002eu006fu0075u0074
    u002eu0070u0072u0069u006eu0074u006cu006eu0028u0020
    u0022u0048u0065u006cu006cu006fu0020u0077u0022u002b
    u0022u006fu0072u006cu0064u0022u0029u003bu007du007d

    The snippet above prints “Hello World” (source: http://stackoverflow.com/questions/30727515/why-is-executing-java-code-in-comments-with-certain-unicode-characters-allowed/30727799#30727799)

  • KevinC

    From that same SO-question as linked below:

    public static void main(String… args) {

    // The comment below is not a typo.
    // u000d System.out.println(“Hello World!”);
    }

    This looks like two commented lines, but u000d is a newline, and thus it prints “Hello World!”.