Is number prime

The problem

A prime number is a number that is only evenly divisible by itself and 1. For example, the number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, however, is not prime because it can be divided evenly by 1, 2, 3, and 6.

Write a method named isPrime, which takes an integer as an argument and returns true if the argument is a prime number, or false otherwise.

Breaking it down

Write a isPrime method

The isPrime method determines whether a number is prime. Primes is a utility class found in apache commons. The Primes.isPrime is already a utility method and in this instance it is being wrapped in the isPrime for illustration purposes.

public static boolean isPrime(int number) {
    return Primes.isPrime(number);

Putting it together

public static void main(String[] args) {

    String message;
    int number;
    Scanner keyboard = new Scanner(;

    // Get the tract in feet.
    System.out.print("Enter a number: ");
    number = keyboard.nextInt();

    // Determine whether it is prime or not.
    if (isPrime(number)) {
        message = "is a prime number.";
    } else {
        message = " is not a prime number.";

    System.out.println("The number " + number
            + message);



Enter a number: 31
The number 31 is a prime number.

Unit tests

public void is_prime() {

public void is_not_prime() {

Level Up

  • Adjust program to enable user to continously enter a number to check
  • Add validation to verify input