# Java program to check for prime and find next Prime in Java

JavaObject Oriented ProgrammingProgramming

Any whole number which is greater than 1 and has only two factors that is 1 and the number itself, is called a prime number. Other than these two number it has no positive divisor. For example: 7 = 1 × 7

Following is the algorithm to find whether a number is prime or not −

• Take integer variable A.

• Divide the variable A with (A-1 to 2).

• If A is divisible by any value (A-1 to 2) it is not prime.

• Else it is prime.

## Example

Following Java program accepts an integer from the user, finds whether the given number is prime and, prints the next prime number.

import java.util.Scanner;
public class NextNumberisPrime {
public static int isPrime(int num){
int prime = 1;
for(int i = 2; i < num; i++) {
if((num % i) == 0) {
prime = 0;
}
}
return num;
}
public static int nextPrime(int num) {
num++;
for (int i = 2; i < num; i++) {
if(num%i == 0) {
num++;
i=2;
} else {
continue;
}
}
return num;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number ::");
int num = sc.nextInt();
int result = 0;
int prime = isPrime(num);
if (prime == 1) {
System.out.println(num+" is a prime number");
} else {
System.out.println(num+" is not a prime number");
}
System.out.println("Next prime number is: "+nextPrime(num));
}
}

## Output

Enter a number ::
25
25 is not a prime number
Next prime number is: 29