Java Algorithm