Java algorithm