Prime Numbers in Java: Simple Logic and Code

Checking whether a number is prime is one of the most common beginner exercises in Java, and for good reason — it's a great way to practice loops, conditionals, and basic optimization thinking all at once.

The Core Logic

A number is prime if it's greater than 1 and divisible only by 1 and itself. The simplest approach checks divisibility from 2 up to the number itself, but a smarter approach only checks up to the square root of the number, since any larger factor would have a corresponding smaller one already checked.

  • Loop from 2 to the square root of the number instead of the full range
  • Immediately return false the moment any divisor is found
  • Handle edge cases: numbers less than 2 are never prime

Why Beginners Practice This

This exercise reinforces how loop boundaries affect performance — a small tweak (checking only up to the square root) can make the same logic run significantly faster on large numbers.

Once you're comfortable with the prime number check, try extending it to print all primes in a range — it's a natural next step that builds on the same logic.

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course