Twin Prime Example Java Program


A twin prime is a prime number that has a prime gap of two. In other words, to qualify as a twin prime, the prime number must be either 2 less or 2 more than another prime number (which by definition would mean that it, too, is a twin prime)?for example, the twin prime pair (41, 43). Two is not considered a twin prime, since it violates the aforementioned rule.

Twin Prime Example Program

import java.util.Scanner;
public class TwinPrime {
    public static void main(String a[]){
        System.out.print("How many twin primes do you need?");
        Scanner in= new Scanner(;
        int input = in.nextInt();
        int i=3,n=35;
        boolean b,task=true;
        int count =0;
            if((isPrime(i)) & ( isPrime(i+2))){   
                System.out.println("  "+(i-2)+"  "+i );
                if(count==input ){
					task = false; }
    public static boolean isPrime(int n) {
    if (n%2==0) return false;//check if n is a multiple of 2
    //if not, then just check the odds
    for(int i=3;i*i<=n;i+=2){
        return false;
    return true;

Sample Output

Output is:
How many twin primes do you need? 8
  1  3
  3  5
  9  11
  15  17
  27  29
  39  41
  57  59
  69  71