Strange, and rarely used Java syntax(s)

What if I told you that the following is perfectly a valid Java code:

public String splitOnDelimiter(String str, String delimiter) [] {
    // Some code logic to fit method name
    return null;

What’s so special about that method declaration? Well, you didn’t notice the [] at the end of method declaration, did you? No, that isn’t a typo. That method has String[] as return type. This is one of those strange Java syntax, that you would only ever use to scare the hell out of some enemy programmer.

Why it works? Because Java allows you to put the brackets after the method declaration, in which case it gets attached to the return type. It is similar to how you are allowed to declare an array variable in two ways:

String[] arr1 = new String[5];
String arr2[] = new String[5];
String[] arr3[] = new String[5][5];  // Easy to guess the method variant of this?

No rocket-science here though. Yes this might feel like one of those useless (yet interesting) blog post 🙂


One Response to Strange, and rarely used Java syntax(s)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: