In this program you will be making use of methods and creating an object of a class and calling the method. So you will see one method by name “isPrime” which takes an integer as an input and returns a boolean value, the returned boolean value evaluates to true if the given input number is a prime and evaluates to false if its not a prime number.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import java.lang.*; public class PrimeNumbers { public static void main(String rs[ ] ) { // creating an object for a class PrimeNumbers pn = new PrimeNumbers(); // calling method printPrimes of class PrimeNumbers, this method takes integer // values as an input, the input says, how many number of prime numbers do you want to print. pn.printPrimes(20); } public void printPrimes(int noOfPrimes) { int primeCount = 0; // below for loop iterates until the value in primeCount is equal to noOfPrimes // which means that the loop is continued until the given number of prime numbers are identified. for(int i=1;primeCount<=noOfPrimes;i++) { // if current value of i is a prime then increment primeCount and print the value of the prime number. if(isPrime(i)) { primeCount++; System.out.println("Prime Number:" + i); } } } // method to find if a given number is a prime or not. public boolean isPrime(int ipNum) { boolean flag = true; // as 1 and 2 are by default prime numbers, we can directly return they are prime numbers. if (ipNum == 2 || ipNum==1 ) return flag; // This loop is used to check if a given number is divisible by numbers other than 1 and itself for(int i=3;i<ipNum/2;i++) { // check if given number is divisible if(ipNum%i==0) { // the moment code flows comes in to this block, it means the give number is divisible by numbers other than 1 and itself flag = false; // as you need not continue the loop, you can break the loop here itself, once you found its not a prime number. break; } } return flag; } } |

There may be more efficient ways of printing the first n prime numbers, we have tried to give the simplest way of doing the same, please feel free to share any queries in form of comments, we would be more than happy to help.