Java Program to check number is prime or not using constructor


In this program, You will learn how to check number is prime or not using constructor in java.


Some list of prime numbers is: 2 3 5 7 11

Test() { 
    //statement
}

Example: How to check number is prime or not using constructor in java.

import java.util.Scanner;

class Test {

    int n, i, p = 1;

    Scanner sc = new Scanner(System.in);

    Test() {
        System.out.print("Enter a number:");
        n = sc.nextInt();
    }

    void checkPrime() {
        for (i = 2; i < n; i++) {
            if (n % i == 0) {
                p = 0;
                break;
            }
        }

        if (p == 1) {
            System.out.println("Number is prime:" + n);
        } else {
            System.out.println("Number is not prime:" + n);
        }

    }
}

class Main {

    public static void main(String args[]) {

        Test obj = new Test();
        obj.checkPrime();

    }
}

Output:

Enter a number:13
Number is prime:13

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.