How to check prime number in Java? [Solved]

Given an integer number, how do you check if its a prime number or not in Java?

Soma
Javarevisited

--

How to check prime number in Java?

Before writing a program to check if a number is prime or not, let's first revise what is a prime number? In Mathematics, a number is said to be prime if it is not divisible by any number other than itself. You can now convert this definition to code and create your Java program to check if given number is prime or not.

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 up-to how many times you want or allow you to stop execution when certain condition is met. Let's see this solution in action.

By the way, if you are new to Java programming language or want to improve Java skills then you can also checkout following best Java courses to get better:

--

--

Soma
Javarevisited

Java and React developer, Join Medium (my favorite Java subscription) using my link 👉 https://medium.com/@somasharma_81597/membership