This blog will illustrate the methodologies to verify if a number is prime in Java.
How to Check/Verify if a Number is Prime Using Java?
To check if a number is prime, apply any of the following approaches:
Approach 1: Check if a Number is Prime in Java Using “if/else” Statement
The “if/else” statement is used to check for a particular condition and return the corresponding outcome upon the satisfied or unsatisfied conditions.
Example
Let’s apply a check for the prime number via the below-stated demonstration:
Apply the following steps in the above code:
- Firstly, initialize the stated integer values in which the former value will be checked for a prime number based on the condition applied with the help of the latter specified value.
- In the next step, specify a flag with a boolean value to refrain from the infinite “while” loop.
- After that, apply the combined “while” loop and the “if” statement to check if the specified number is completely divisible by “2”.
- If so, the flag will become “true” and the “else” condition will execute.
- Otherwise, the number will be found out to be “prime”, thereby falsifying the flag and so the “if” statement will come into effect.
Output
In the above output, it can be observed that “15” is found to be a non-prime number which is true.
Approach 2: Check if a Number is Prime in Java Using “for” Loop
In this particular approach, the “for” loop can be applied to iterate through the first prime number and apply a check upon the specified number for the required condition accordingly.
Example
Go through the below-stated lines of code:
In the above demonstration, apply the following steps:
- First of all, initialize the integer value that needs to be checked for a prime number and likewise assign a “flag”.
- After that, apply the “for” loop to iterate from “2” till half of the given number since the number is not divisible by more than its half.
- Now, similarly check for the complete divisibility check by “2”, as discussed in the “if” statement.
- If this condition is satisfied, the number will be found to be not prime.
- Else, the latter “if” statement executes, indicating that the specified number is prime.
Output
The above output signifies that the applied check is performing appropriately.
Conclusion
To check if a number is prime in Java, apply the “if/else” statement or the “for” loop. These approaches can be utilized to simply apply a check upon the specified number by allocating a flag and invoking the corresponding statements upon the satisfied and unsatisfied condition. This write-up discussed the approaches to verify if a number is prime in Java.