Prime Number in Java

In this Java Tutorial, we will learn how to write a Java program to get the prime numbers from 1 to the given number.

Prime Number in Java

In this Java tutorial , you will learn how to write a Java program to get prime numbers between 1 to the desired number.

To start with, we have defined a class "PrimeNumber" in this example. Java I/O package has both input as well as output stream. The input stream is used to read the stream and to allocate the memory, while the output stream is used to write the bytes.

In this example of writing java program to get prime numbers, we will insert some instructions by creating buffer reader class. To proceed with, we will have to create a buffer for the string class, which can be used to instantiate a changeable object in order to store and process a string of character.

After that, we have used the ParseInt method to convert the parses into the string argument and define 'num' as an integer.

Now to execute the program, we have used two 'for' loop. For loop will start from 1 to entered number. And another loop will start and divide it from 2 to less than those numbers. Moreover, if the number is divisible by any number, it means it is not prime otherwise prime number.


Here is the code of the java Program to get prime numbers:


class PrimeNumber {
  public static void main(String[] args) throws Exception{
  int i;
  BufferedReader bf = new BufferedReader(
  new InputStreamReader(;
  System.out.println("Enter number:");
  int num = Integer.parseInt(bf.readLine());
  System.out.println("Prime number: ");
  for (i=1; i < num; i++ ){
  int j;
  for (j=2; j < i; j++){
  int n = i%j;
  if (n==0){
  if(i == j){
  System.out.print( "  "+i);



We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.

Share on Google+Share on Google+

Prime Number in Java

Posted on: October 10, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Prime Number in Java  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
October 27, 2013