Java code for basic algorithm