Implementing in java using recursion