# Java program to Find whether number is Prime or Not

```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class PrimeNo{ public static void main(String args[]){ int num = Integer.parseInt(args); int flag=0; for(int i=2;i<num;i++){ if(num%i==0) { System.out.println(num+" is not a Prime Number"); flag = 1; break; } } if(flag==0) System.out.println(num+" is a Prime Number"); } }```

### 33 Responses to “Java program to Find whether number is Prime or Not”

1. Suryansh Srivastava

import java.util.*;
class prime_number
{
static Scanner sc = new Scanner (System.in);
public static void main()
{
System.out.print(“Enter A Number : “);
int n=sc.nextInt();

if(n==2)
{
System.out.println(“\n2 is a prime number”);
}
for(int i=2;i<n;i++)
{
if(n%i==0)
{
System.out.print("\n"+n+" is not a prime number");
break;
}
else
{
System.out.print("\n"+n+" is a prime number");
break;
}
}
}
}

Reply
2. Shetty Pramod

the for loop should be continued only till n/2, because a number after this cannot divide n.

Reply
• Suryansh Srivastava

Yea , but it wont’s work for 3 and 5 . Check it.

Reply
3. haritha

why you will use scanner object

Reply
4. hariprasanth

import java.util.*;
import java.io.*;

public class one
{
public static void main(String args[])
{
int num;
int flag=0;
System.out.println(“Enter an integer to check ?”);
Scanner in = new Scanner(System.in);
num = in.nextInt();

for(int i=2;i<num;i++){
if(num%i==0)
{
System.out.println(num+" is not a Prime Number");
flag = 1;
break;
}
}
if(flag==0)
System.out.println(num+" is a Prime Number");
}
}

Reply
• Abhishek

What is the use of flag here?

Reply
5. why did you use the flag .why did you assign 0 and 1 in the flag.it is only comes under true or false statement.

Reply
6. In first 2 is considered as non prime no…!

Reply
7. very bad site

wertyuiko;
nm,.ertyui

Reply
8. very bad site

c j h j u j d

Reply
9. very bad site

Reply
10. all use less programs

Reply
##### More from Basic Programs
###### Java program to find whether no. is palindrome or not ### Research Papers

Click Here to Submit ### Projects

Click Here to Submit

##### Free email signup

Get latest projects, articles in your mail box, subscribe to electrifriends

Email:
##### Technical Papers 