All you need to do is create a method like public boolean isPrimeNumber(int number). This method should accept an integer number and return a boolean value true or false depending upon whether given number is prime or not.
The logic of method should check starting from the first prime number to the number itself whether the given number is divisible by any number in between or not. You can use for loop to code this part. The loop gives you luxury to repeat an action upto how many times you want or allow you to stop execution when certain condition is met. Let's see this solution in action.
How to find if a number is Prime in JavaBased upon the definition of "prime numbers", here is the code which checks if given number is prime or not in Java:
It's simple and easy to understand, but it's not efficient because mathematically it's only required to check upto square root of a number to determine if it's prime or not. That will improve the execution time of this solution by double because square root is often less than or equal to halft of the number itself. I have used that as our preffered solution in this program, which you will see in next section.
Java Program to find if a number is Prime or Not
That's about it. Now, you know how to check if a given number is a prime number or not. As I said there are many sophisticated algorithm exists to find prime numbers upto a given number e.g. Sieve of Eratosthenes.
If you ever need an array of prime numbers, you should be using Sieve of Eratosthenes, instead of obtaining the maximum number and check each number upto that is prime or not. That would not be as efficient as Sieve of Eratosthenes.
This solution is purely for teaching and educational purpose, basically to teach a non-programmer to code.