Algorithm in java.