Prime Number Program in JavaLast Updated : 31 Jan 2026 A prime number is a number that is greater than 1 and divided by 1 or itself. In other words, prime numbers cannot be divided by other than itself or 1. For example, 2, 3, 5, 7, 11, 13, 17... are the prime numbers. Note: 0 and 1 are not prime numbers. The number 2 is the only even prime number because all the other even numbers can be divided by 2.AlgorithmPrime Number Java ProgramIn this Java program, we will take a number variable and check whether the number is prime or not. ExampleCompile and RunOutput: 3 is a prime number Prime Number Program Using User-Defined MethodIn the following program, we have defined a method to check if the number is prime or not. ExampleCompile and RunOutput: 1 is not a prime number 3 is a prime number 17 is a prime number 20 is not a prime number Prime Number Program in Java (Optimized Approach)The following approach is a bit different from the above one. In the following program, we have implemented the logic efficiently using Math.sqrt(n) to reduce unnecessary iterations. It is an optimized approach. ExampleCompile and RunOutput: 67 is a prime number Find Prime Numbers Between Two NumbersWe can also find prime numbers between two specified numbers. ExampleCompile and RunOutput: prime numbers between 2 and 10 are: 2 3 5 7 Next TopicJava Programs |
We request you to subscribe our newsletter for upcoming updates.

We deliver comprehensive tutorials, interview question-answers, MCQs, study materials on leading programming languages and web technologies like Data Science, MEAN/MERN full stack development, Python, Java, C++, C, HTML, React, Angular, PHP and much more to support your learning and career growth.
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India