The following table provides few examples of prime numbers.

Number

Divisor

Result

13

1, 13

Prime Number

15

1, 3, 5, 15

Not a Prime Number

47

1, 47

Prime Number

Using for loop

In the following example, we will check whether the given number (7) is a Prime number or not using for loop.

Example

Java Compiler

public class myClass
{
public static void main(String[] args)
{
int num =7;
int i =1;
int count =0;
for(i=1; i<=num; i++)
{
if(num % i ==0)
count++;
}
if(count ==2)
System.out.format("%d is a prime number", num);
elseSystem.out.format("%d is not a prime number", num);
}
}

Output

7 is a prime number

Using while loop

In the following example, we will check whether the given number (7) is a Prime number or not using while loop.

Example

Java Compiler

public class myClass
{
public static void main(String[] args)
{
int num =7;
int i =1;
int count =0;
while(num >= i)
{
if(num % i ==0)
count++;
i++;
}
if(count ==2)
System.out.format("%d is a prime number", num);
elseSystem.out.format("%d is not a prime number", num);
}
}

Output

7 is a prime number

Using do while loop

In the following example, we will check whether the given number (7) is a Prime number or not using do while loop.

Example

Java Compiler

public class myClass
{
public static void main(String[] args)
{
int num =7;
int i =1;
int count =0;
do {
if(num % i ==0)
count++;
i++;
}while(i <= num);
if(count ==2)
System.out.format("%d is a prime number", num);
elseSystem.out.format("%d is not a prime number", num);
}
}

Output

7 is a prime number

Prime Numbers between the Given Range

In the following example, we will find all the Prime numbers between 1 and 20.

Example

Java Compiler

public class myClass
{
public static void main(String[] args)
{
int start =1;
int end =20;
int count =0;
int i =1;
System.out.println("Prime numbers between 1 and 20:");
for(start=start; start<=end; start++)
{
for(i=1; i<=start; i++)
{
if(start % i ==0)
count++;
}
if(count ==2)
System.out.print(start +" ");
count =0;
}
}
}

Output

Prime numbers between 1 and 20:
2 3 5 7 11 13 17 19

Check Whether the Given Number is Prime or Composite

In the following example, we will check whether the given number is a Prime number or Composite number.

Example

Java Compiler

import java.util.Scanner;
public class myClass
{
public static void main(String[] args)
{
Scanner reader =new Scanner(System.in);
System.out.print("Enter a (int) Number: ");
int num = reader.nextInt();
int i;
int count =0;
for(i=1; i<=num; i++)
{
if(num % i ==0)
count++;
}
if(count ==2)
System.out.format("%d is a prime number", num);
elseSystem.out.format("%d is a composite number", num);
}
}

Output

Enter a (int) Number: 17
17 is a prime number

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on Java with examples for quick and easy learning.

We are working to cover every Single Concept in Java.