A prime number is a number which is distinct by just two numbers: 1 and itself. In this way, if any number is distinct by some other number, it's anything but a prime number.

Program to Check Prime Number using a for loop

public class Prime {

public static void main(String[] args) {

int num = 29;
boolean flag = false;
for(int i = 2; i <= num/2; ++i)
{
// condition for nonprime number
if(num % i == 0)
{
flag = true;
break;
}
}

if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}

When you run the program, the yield will be:

29 is a prime number.

In the above program, for circle is utilized to decide whether the given number num is prime or not. We just need to circle through 2 to half of num, in light of the fact that no number is distinguishable by more than its half.

Inside the for circle, we check if the number is distinguishable by any number in the given range (2..num/2). On the off chance that it is, signal is set to genuine and we break unware of present circumstances. This decides num is certainly not a prime number.

On the off chance that num isn't distinguishable by any number, signal is false and num is a prime number.

Java Program to Display Fibonacci Series

Program to Check Prime Number using a while loop

public class Prime {

public static void main(String[] args) {

int num = 33, i = 2;
boolean flag = false;
while(i <= num/2)
{
// condition for nonprime number
if(num % i == 0)
{
flag = true;
break;
}

++i;
}

if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}

When you run the program, the yield will be:

33 is anything but a prime number.

In the above program, while circle is utilized rather than a for circle. The circle keeps running until I <= num/2. On every emphasis, regardless of whether num is divisble by I is checked and the estimation of I is increased by 1.

Top 5 Books for Learn Core Java for Beginners