This example will show how to check if a number is a prime using various straight up java techniques and apache commons.

Straight up Java

Is prime

This approach is often found in beginning java exercises where a question is asked to write a program to determine if a number is prime. A method is created with a number as parameter where the first if check is created to check if the number is divisible by 2. If it is the method returns false otherwise it proceed checking if the number can be divided by any number that is contained in the number incrementing by 2.

BigInteger probable prime

Is prime regular expression

This regular expression will check if a number isPrime.

Apache Commons

Apache commons has a dedicated class for checking if a number is prime which contains various methods to check if a number isPrime, finding the next prime and finding the prime factors for a given number.