Different way to declare method return type

Here is a different way that I have encountered from the stackoverflow answer (thanks to Chandra Patni). I am happy to share it here. This works specifically for arrays, if you want to trick your friends writing a method that returns an array weirdly, then this is the best thing to get them awestruck and probably get lost in a state of confusion (provided they aren't familiar with it), otherwise sure, they'll laugh at you for knowing it lately. Now, shall we get into the program, a simple one, really simple?

class DifferentReturn
{
    public static void main(String args[])
    {
        System.out.println(nums().length);
    }
   
    public static int nums()[]{
        return new int[]{1,2,3,4,5};
    }
}

The method is same as int[] nums(). All you did is just shifted the square brackets. That is what that makes it weird.


Posted by at on

Tags: Tricks Bag,