# Java methods to check for prime and find the next prime

JavaObject Oriented ProgrammingProgramming

The java.math.BigInteger class provides operations analogues to all of Java's primitive integer operators and for all relevant methods from java.lang.Math. It also provides methods to verify if a number is prime and, a method to find next probable prime.

isProbablePrime() − This method accepts an integer value representing the certainty and verifies whether value represented by the current object is a prime number. It returns a boolean value which is −

• true, if the given number is prime.

• false, if the given number is not prime.

## Example

Live Demo

import java.math.BigInteger;
import java.util.Scanner;
public class isProbablePrimeExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number :");
long num = sc.nextLong();
int result = 0;
BigInteger bigInt = new BigInteger(String.valueOf(num));
boolean prime = bigInt.isProbablePrime(1);
if (prime) {
System.out.println(num+" is a prime number");
} else {
System.out.println(num+" is not a prime number");
}
}
}

## Output1

Enter a number :
25
25 is not a prime number

## Output2

Enter a number :
19
19 is a prime number

nextProbablePrime() − this method returns the next first prime number (integer) greater than the current BigInteger.

## Example

Live Demo

import java.math.BigInteger;
import java.util.Scanner;
public class nextProbablePrimeExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number :");
long num = sc.nextLong();
int result = 0;
BigInteger bigInt = new BigInteger(String.valueOf(num));
BigInteger prime = bigInt.nextProbablePrime();
System.out.println("Next prime number : "+prime.intValue());
}
}

## Output

Enter a number :
25
Next prime number : 29