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.
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.
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.
// if current value of i is a prime then increment primeCount and print the value of the prime number.
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
// check if given number is divisible
// 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.
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.
Founder of TestingTools.co, constantly shares knowledge on different test automation tools. Has experience in building proof of concepts, solutions, frameworks, platforms & implementation of test automation projects.
In pursuit of building a platform with inbuilt framework and reusable components for Oracle Cloud applications ( Oracle HCM, CX, SCM, Financials clouds, Salesforce and other cloud applications )
Major accomplishments in his career:
Product architect and development manager for test automation platforms
Oracle Flow Builder @ Oracle
CloudTestr @ Suneratech
2 times to oracle open world
More than 20 successful POCs ( Proof of concepts )
Designed pricing models.
Trained more than 50 members.
Built more than 100 re-usable functions.
Worked with tools: