Back to: Java Tutorials
Here is an example of Java code to check if a given number is a prime number or not:
public class PrimeNumber {
public static void main(String[] args) {
int n = 17;
if (isPrime(n)) {
System.out.println(n + " is a prime number");
} else {
System.out.println(n + " is not a prime number");
}
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
In this code, the main
function initializes the variable n
to 17 and then calls the isPrime
function to check if it is a prime number. If the function returns true
, then the program prints a message saying that the number is prime, otherwise it prints a message saying that the number is not prime.
The isPrime
function takes an integer n
as input and returns a boolean value indicating whether n
is a prime number or not. The function first checks if n
is less than or equal to 1, which is not a prime number. Then, it uses a for loop to iterate from 2 to the square root of n
, checking if n
is divisible by any number in that range. If n
is divisible by any number in the range, then it is not a prime number and the function returns false
. Otherwise, the function returns true
.
When this code is executed, it will output the message “17 is a prime number” to the console.
In conclusion, this Java code checks if a given number is a prime number using a for loop and the square root function. The code can be modified to take user input for the value of n
or to output all prime numbers within a given range.
Follow us on social media
Follow Author