Prime Number program in Java will print the prime numbers between 1 to any given number.
Prime Number is a number that is not divisible by any number other than 1 or itself. Similar logic is used in program will displaying the result.
At first PrimeNumber class is defined. We create a main() method. Here in the example we have taken 50 as the value of int, programmers can use any value here. Then for loop is created.
The following is a simple program, which automatically prints Prime Number starting from 1 to 50.
Example of Prime Number program in Java:package Tutorial; public class PrimeNumber { public static void main(String[] args) { int num = 50; System.out.println("prime number from 1 to " + num ); for (int i = 1; i < 50; i++) { boolean b = true; for (int j = 2; j < i; j++) { if (i % j == 0) { b = false; break; } } if (b) System.out.print(i + " "); } } }
Output:
Prime Number from 1 to 50
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial

Discuss: Prime Number program in Java
Post your Comment