Tutorials

# Java Next Prime

In this java tutorial programming tutorial, our task is to write a simple java program:

• to find out the next immediate prime number
• if the given number is itself a prime then print it as next prime.

Example:

Given number: 8

Next immediate Prime is: 11

What is a prime number?

A whole number which is greater than 1 and has only two factors which includes 1 and the number itself is a prime number.

Few examples are 2, 3, 5, 7,11,13, 17, 19, 23

### Java program to find the next immediate prime to given number.

``````

public static void main(String[] args) {

int num = 8;
int prime = 0;  //next prime will be assigned to this var

for(int j = num; j<15; j++){  //outer loop

int count = 0;
for(int i=2; i<=j/2; i++){  //inner loop

if(j%i==0){
count++;
}
}

if(count==0){

prime = j;   //assign next prime
break;

}

}

System.out.println(prime);

}

}``````

OUTPUT

11

### How the above code works?

• Given number is 8. Though we hard coded this, you may use scanner to let user enter value of their choice.
• prime variable will hold the value of next prime number to 8.
• The outer for loop will start iteration from the given number itself. (to see if the given number is prime or not)
• The inner for loop will iterate from 2 to half of outer loops counter at current iteration which in progress.
• Now inside inner loop, we check if any of the inner loops iteration (i) is able to completely divide the outer loop number (j) then we increase count by 1. Everytime j%i==0, the counter will increase as count++.
• At the end of the inner loop we check, if(count==0), then assign value of j to the prime. If count is 0 that means that j was not divisible by any other number. This indicates that current iterations value of j is prime number.
• Since we need to print only the next immediate prime, so we apply break, to terminate the outer loop. If we don't apply break then other prime numbers following next will also get printed. For example, 11,13

### Java program to find the prime numbers between 1 to 100.

``````package basic;

public class prime1to100 {

public static void main(String[] args) {

for(int j = 2; j<100; j++){  //outer loop

int count = 0;
for(int i=2; i<=j/2; i++){  //inner loop

if(j%i==0){
count++;
}
}

if(count==0){

System.out.println(j);;   //assign next prime

}

}

}

}``````

OUTPUT

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

Practice programs:

1. Write a java program to verify if the given number is prime number or not.
2. Write a java program to verify if the given number is odd.
3. Write a java program to verify if the given number is even.