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 read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.