Twin Prime Example in Java
On this page (9sections)
Introduction
Twin Prime is a classic Java console program that demonstrates the concept with complete source code and sample output. These programs cover your first Java class, constructors, methods and simple OOP building blocks.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
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(System.in);
int input = in.nextInt();
int i=3,n=35;
boolean b,task=true;
int count =0;
while(task){
if((isPrime(i)) & ( isPrime(i+2))){
count++;
System.out.println(" "+(i-2)+" "+i );
if(count==input ){
task = false; }
}
i+=2;
}
}
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){
if(n%i==0)
return false;
}
return true;
}
}
Sample Output
How many twin primes do you need? 8
1 3
3 5
9 11
15 17
27 29
39 41
57 59
69 71
When to use
Use this twin prime example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.util.Scanner;imports a class used later in the program. -
A
println/printcall writes text to the console — part of the sample output below. -
A
Scannerreads typed input from the keyboard (System.in). -
int input = in.nextInt();updates a variable used in the calculation or output. -
int i=3,n=35;updates a variable used in the calculation or output. -
boolean b,task=true;updates a variable used in the calculation or output. -
A loop repeats the block until its condition becomes false.
Best Practices
- Name classes in PascalCase and follow one public class per file when starting out.
- Keep
mainshort — delegate work to other methods as programs grow.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.