Here's a code snippet I wrote in C++ that might be interesting to you.
http://www.daniweb.com/code/snippet217218.html
It has a different approach than your program. There are many different ways to do this. The snippet above is written in C++, but the logic would apply to Java too.
As far as your program goes, you break the loop by assigning a new value to i, which works. Another way to get out of a loop early is to use the "break" statement.
http://java.sun.com/docs/books/tutor...ts/branch.html
In line 18, you have a square root calculation that takes place every trip through the loop, but really only need to take place once. If you take it outside of the loop, it could speed things up.
// slower
for (int i = 2; i <= Math.sqrt (n); i++)
{
// loop code
}
// faster
double squareRootn = Math.sqrt (n);
for (int i = 2; i <= squareRootn; i++)
{
// loop code
}
The square root calculation is a CPU-intensive calculation. If n is a billion, you'd be taking that square root of a billion over 30,000 times in the top version as opposed to once in the lower version (it's possible that the compiler could possibly figure this out on its own and optimize for you, but don't count on it).
Finally, consider the fact that the only even prime number is 2, so you could redesign your loop so that it increases by 2 each time rather than 1 to take advantage of that fact. True, even numbers will be detected very quickly in your code and calculating the mod of a number base 2 is a speedy calculation, but you can skip it altogether if you don't even bother to test 4, 6, 8, ...