Thursday, November 5, 2015

Secret Way of Returning Array from Method in Java

Introduction

This post is like a little travel in time. It is quite short and doesn't bring a lot of practical sense, but rather a small historical trick that was known better in the early days of Java. So without further ado let me show you ancient and deprecated but still working way of declaring a method that returns an array.

Traditional Way

Just for completeness let me give a small example of traditional syntax used to define a method which returns an array in Java:
int[] traditionalMethod() {
    return new int[] {1, 2, 3};
}

Old School Way

And here is the old school way which was better known in the early days of Java, but now can be found probably only in JLS:
int oldSchoolMethod() [] {
    return new int[] {1, 2, 3};
}
Notice how squared brackets are placed after parentheses. It is worth noting that this way of declaring a method which returns an array is considered deprecated, but I think it is still interesting to know this old funny trick :)

No comments:

Post a Comment