How to check if a number is prime in Java?

To check if a number is prime in Java, check whether this number divides by any number before it, using the for loop.

Here's how you do it:

public class IsPrime {

  public static void main(String[] args) {
    System.out.println(isPrime(1)); // false
    System.out.println(isPrime(4)); // false
    System.out.println(isPrime(31)); // true
    System.out.println(isPrime(53)); // true
    System.out.println(isPrime(52)); // false

  static boolean isPrime(int n) {
    if (n <= 1) return false;
    for (int i = 2; i < n; i++) if (n % i == 0) return false;
    return true;