Java Program - Check if a Number is Prime
A basic program to determine if a given number is a prime number.
A basic program to determine if a given number is a prime number.
This Java program checks whether a given number (in this case, 29) is a prime number. It initializes a boolean variable isPrime to true and uses a for loop to iterate from 2 to number / 2. If the number is divisible by any value in this range (number % i == 0), it sets isPrime to false and breaks out of the loop. After the loop, it prints whether the number is prime based on the value of isPrime. If isPrime remains true, the number is prime; otherwise, it is not.
29
29 is a prime number.
public class PrimeCheck {
public static void main(String[] args) {
int number = 29;
boolean isPrime = true;
for (int i = 2; i <= number / 2; ++i) {
if (number % i == 0) {
isPrime = false;
break;
}
}
if (isPrime)
System.out.println(number + " is a prime number.");
else
System.out.println(number + " is not a prime number.");
}
}
29 is a prime number.
import java.util.Scanner; public class PrimeCheck { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); boolean isPrime = true; if (number <= 1) { isPrime = false; } else { for (int i = 2; i <= number / 2; ++i) { if (number % i == 0) { isPrime = false; break; } } } if (isPrime) System.out.println(number + " is a prime number."); else System.out.println(number + " is not a prime number."); } }
Scanner: Imports the Scanner class to read user input.Scanner scanner = new Scanner(System.in); creates a Scanner object to read input from the console.int number = scanner.nextInt(); reads an integer input from the user.First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.