O'Reilly logo

Programmer's Guide to Java™ Certification, A: A Comprehensive Primer, Second Edition by Rolf W. Rasmussen, Khalid A. Mughal

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5. Control Flow, Exception Handling, and Assertions

5.1 Finding primes using for-loops.
// Filename: ForPrimes.java
public class ForPrimes {
    final static int MAX = 100;
    public static void main(String[] args) {
        numbers:
        for (int num = 1; num < MAX; num++) {
            int divLim = (int) Math.sqrt(num);

            for (int div = 2; div <= divLim; div++)
                if ((num % div) == 0) continue numbers;
            System.out.println(num);
        }
    }
}

Finding primes using while-loops.

 // Filename: WhilePrimes.java public class WhilePrimes { final static int MAX = 100; public static void main(String[] args) { int num = 1; numbers: while (num < MAX) { int number = num++; int divLim = (int) Math.sqrt(number); int div = 2; while (div <= divLim) if ((number % div++) == 0) continue numbers; System.out.println(number); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required