Java program to print Twin Prime Numbers

Java program to print Twin Prime Numbers

Write a program in java to enter two numbers and check if they are twin prime numbers or not.

Twin Primes are the prime numbers with a difference of 2, e.g., (3, 5), (5, 7), (11, 13), (17, 19), (29, 31) ... etc. 

In this program isPrime(int n) will return true if the number is prime and false if it is not prime. This method is called in the main() method which checks the numbers are prime or not and also the difference between two prime numbers is 2. And if it is then it called Twin prime number.

// Program to check twin prime
public class TwinPrimeNumber
        public static boolean isPrime(int n)
            // boolean value will return
            boolean f = true;

            for (int i = 2; i <= n / 2; i++) {
                if (n % i == 0) {
                    f = false;

            return f;

        // main method begins
        public static void main(String args[]) throws IOException

            int number1, number2;
            // InputStreamReader object
            InputStreamReader in = new InputStreamReader(;
            // BufferedReader object
            BufferedReader br = new BufferedReader(in);    
            System.out.print("Enter first number: ");
            // First number
            number1 = Integer.parseInt(br.readLine());
            System.out.print("Enter second number: ");
            // Second number
            number2 = Integer.parseInt(br.readLine());

            // Checking both the number is prime and the difference between two is 2
            if (isPrime(number1) == true && isPrime(number2) == true && Math.abs(number2 - number1) == 2) {
                System.out.println("Twin prime number");
            } else {
                System.out.println("Not twin prime numbers");

        } // end method main
    } // end class

Enter first number: 11
Enter second number: 13
Twin prime number

Enter first number: 9
Enter second number: 11
Not twin prime numbers

In the above program, a method public static boolean isPrime(int n) is used to check prime numbers. This method return a boolean value. If the number is prime then it will send true otherwise false. In main() method isPrime called two times to check true or false. 

//Twin prime number without method

import java.util.*;
public class TwinPrime
    public static void main(String args[])
        int n1, n2, i, f1,f2;
        Scanner sc=new Scanner(;
        System.out.println("Enter First number:");
        System.out.println("Enter Second number:");
        for(i=2; i<n1; i++)
        for(i=2; i<n2; i++)
        if(f1==1 && f2==1 && Math.abs(n1-n2)==2)
            System.out.println("Twin Prime Number");
            System.out.println("Not a Twin Prime Number");

More Program

Previous Post
Next Post