---
title: "Java program to check if the given number is Prime?"  
description: "Java program to check if the given number is Prime?"  
author: "Mukul Goenka"  
published: 2021-11-16  
updated: 2023-04-18  
canonical: https://www.mindstick.com/forum/156843/java-program-to-check-if-the-given-number-is-prime  
category: "java"  
tags: ["java", "programming language"]  
reading_time: 2 minutes  

---

# Java program to check if the given number is Prime?

[Java](https://www.mindstick.com/articles/12214/web-development-company-in-india-laid-on-the-foundation-of-concrete-java-programming) [program to check](https://www.mindstick.com/forum/157542/write-a-java-program-to-check-if-a-list-of-integers-contains-only-odd-numbers) if the given number is Prime?

## Replies

### Reply by Krishnapriya Rajeev

Given below is the code to [check if](https://www.mindstick.com/forum/12878/how-to-check-if-an-asp-dot-net-file-upload-control-has-a-file-in-jquery) a given number is prime or not.

```plaintext
class prime{
  public static void main(String args[]){
    int n = 139;
    if(isPrime(n)){
    System.out.println(n+" is prime.");
  }
    else{
      System.out.println(n+" is not prime");
    }
  }
  //Function to check if a number is prime or not
  static boolean isPrime(int n){
    int mid = n/2;
    if(n == 0 || n == 1){
      return false;
    }
    for(int i = 2; i <= mid; i++){
      if(n%i == 0){
        return false; //Returns false if the number is divisible by any number
      }
    }
     return true; //Returns true if the number is not divisible by any other number other than 1 and the number itself
  }
}
OUTPUT
139 is prime
```

### Reply by Mukul Goenka

```
public class PrimeNumberCheck {
 public static void main(String[] args) {
  System.out.println(isPrime(19)); // true
  System.out.println(isPrime(49)); // false
 }
 public static boolean isPrime(int n) {
  if (n == 0 || n == 1) {
   return false;
  }
  if (n == 2) {
   return true;
  }
  for (int i = 2; i <= n / 2; i++) {
   if (n % i == 0) {
    return false;
   }
  }
  return true;
 }
}
```

Output.

true

false


---

Original Source: https://www.mindstick.com/forum/156843/java-program-to-check-if-the-given-number-is-prime

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
