Prime Number Program in Java

Here’s a simple program in Java to check if a number is prime or not:

Explanation:

  1. The program asks the user to enter a number using the Scanner class.
  2. The isPrime variable is initialized to true, assuming the number is prime.
  3. The program checks if the number is divisible by any number from 2 to half of the number using a for loop.
  4. If the number is divisible by any of these numbers, the isPrime variable is set to false, and the loop breaks.
  5. After the loop ends, the program checks the value of isPrime and prints the appropriate message indicating whether the number is prime or not.

Here’s a version of the prime number program in Java 8 using lambda expressions and the IntStream API:

Explanation:

  1. The program asks the user to enter a number using the Scanner class.
  2. The isPrime variable is determined using the IntStream API.
  3. The IntStream.range method generates a stream of numbers from 2 to the square root of the given number.
  4. The noneMatch method checks if none of the numbers in the stream divide the given number evenly.
  5. The isPrime variable is set to true if the number is greater than 1 and no divisors are found.
  6. Finally, the program prints the appropriate message based on the value of isPrime.

This program uses the functional programming features introduced in Java 8, making it concise and readable. It leverages the power of streams and lambda expressions to perform the prime number check efficiently.

About Manohar

I, Manohar am the founder and chief editor of ClarifyAll.com. I am working in an IT professional.

View all posts by Manohar →

Leave a Reply