# Java Program to display a prime number less than the given number

Java 8Object Oriented ProgrammingProgramming

Let’s say the value you have set is 20 and you have to display a prime number less than this value i.e. 19 in this case.

The following is an example that displays a prime number less than the given number −

## Example

Live Demo

public class Demo {
public static void main(String[] args) {
int val = 20;
boolean[] isprime = new boolean[val + 1];
for (int i = 0; i<= val; i++)
isprime[i] = true;
// 0 and 1 is not prime
isprime = false;
isprime = false;
int n = (int) Math.ceil(Math.sqrt(val));
for (int i = 0; i<= n; i++) {
if (isprime[i])
for (int j = 2 * i; j<= val; j = j + i)
// not prime
isprime[j] = false;
}
int myPrime;
for (myPrime = val; !isprime[myPrime]; myPrime--); // empty loop body
System.out.println("Largest prime less than or equal to " + val + " = " + myPrime);
}
}

## Output

Largest prime less than or equal to 20 = 19

Above, we have set the following as non-prime since both 0 and 1 are non-prime −

isprime = false;
isprime = false;