Java Code for printing PrimeNumbers between two numbers

Write a java program to print prime numbers between 1 and 100. Java beginners may be asked to write this program when they start to learn about loop. The following code  prints prime numbers between two numbers. As we know, Prime Number is the number which is divided by 1 and itself. It accepts two numbers as command line arguments and prints the prime numbers between the given two numbers. You can run the below program online at http://ocr.javaonlineguide.net/ocr/RunExample?fname=PrimeNumbers

import java.io.*;

package com.javaonline;

class PrimeNumbers {

public static void main(String[] args) {

	int i;

try{

		if (args.length!=2)
		{
			System.out.println("Incomplete Input");
			return;
		}

		int number1= Integer.parseInt(args[0]);

		int number2= Integer.parseInt(args[1]); // accepts second number

		System.out.println("Prime Numbers between "+ number1 + " and " + number2);

			for (int j=number1 ; j<=number2 ; j++)

			{

				for (i=2; i < j ;i++ ){

				int n = j%i;

				if (n==0){

				break;

			}

		}

		if(i == j){

			System.out.print( j+ " ,");

		}

		}

}
catch (Exception e)

{

System.out.println("Error");

}

}

} 

Run the program with command line arguments 1 & 100.  The below output will be displayed.

Prime Numbers between 1 and 100

 

 

 

 

 

You may also like