A huge optimization could be made by storing and int array of already found primes and test all primes smaller then half the to-test number. this will speed up a lot. Another huge improvement could be made with hardcoding everything up to the prime 3 and then iterate with intervals of 2 instead of 1.