Prime Number Check in Java: Explanation & Practice

Check if a number is prime

Problem summary

Write a program that checks if a given number is prime. Your code should work for ANY positive integer.

Starter code

public class Main {
    public static void main(String[] args) {
        int number = 17; // Test case 1
        
        // Check if number is prime
        // Print: Is prime: <true/false>
    }
}

Expected output and test cases

  • 17 is prime
    Is prime: true
  • 18 is not prime
    Is prime: false
  • 1 is not prime
    Is prime: false

Hints

  1. A prime has exactly 2 factors: 1 and itself
  2. Check divisibility from 2 to sqrt(n)
  3. 1 is NOT a prime number

Related Control Flow exercises

Practice all Control Flow exercises · Run this idea in the Java compiler