Algorithm using Java