algorithm in Java