Java algorythm